在字符串某个位置插入子字符串
- 示例 1:
/*
str:原字符串
index:指定插入的索引文字
insertStr:要插入的字符串
*/
function insertStr (str, index, insertStr) {
const ary = str.split(''); // 转化为数组
ary.splice(index, 0, insertStr); // 使用数组方法插入字符串
return ary.join(''); // 拼接成字符串后输出
}
console.log(insertStr("ac",1,"b"))
// "abc"
- 示例 2:
function insertStr (str, index, insertStr) {
return str.substring(0, index) + insertStr + str.substring(index)
}
console.log(insertStr("ac",1,"bb"))
// "abbc"