在 JavaScript 中,在一个字符串的特定位置插入另一个字符串

在 JavaScript 中,在一个字符串的特定位置插入另一个字符串

方法一:使用 slice() 或 substring() 结合字符串拼接

这是最基本的方法,通过将原始字符串分割成两部分,然后在这两部分之间插入新的字符串。
{
  // 传入索引
  function insertStr(source, insert, index) {
    return source.slice(0, index) + insert + source.slice(index);
  }
  // 使用示例
  let original = "Hello World";
  let toInsert = ", beautiful";
  // let position = 5; //
  let position = original.search(" World"); // 查找索引
  let result = insertStr(original, toInsert, position);
}

方法二:使用 replace 正则表达式(适用于基于模式的插入)replace

如果插入位置是基于某个模式而不是固定的索引,可以使用正则表达式。
{
  function insertStrByPattern(source, insertPos, insert) {
    let pattern = new RegExp(insertPos);
    return source.replace(pattern, (match) => match + insert);
  }

  // 使用示例
  let original = "Hello World";
  let insertPos = "World";
  let toInsert = " beautiful";

  let result = insertStrByPattern(original, insertPos, toInsert);
  console.log("🚀 ~ file: App.vue:33 ~ result:", result);
}

方法三:使用数组方法

将字符串转换为数组,然后使用数组的 splice() 方法插入新字符串,最后再将数组转回字符串。
{
  function insertStrUsingArray(source, insert, index) {
    let arr = source.split("");
    arr.splice(index, 0, ...insert.split(""));
    return arr.join("");
  }
  
  // 使用示例
  let original = "Hello World";
  let toInsert = ", beautiful";
  // let position = 5;
  let position = original.search(" World"); // 查找索引
  
  let result = insertStrUsingArray(original, toInsert, position);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值