var str = '#张三#我这里有物资#李四#前方有敌人#王五#不要怂,一起上';
var tempArr = [];
var pos = str.indexOf("#");
while(pos > -1){
tempArr.push(pos);
pos= str.indexOf('#',pos+1);
}
console.log(tempArr);
function insertStr(soure, start, newStr){
return soure.slice(0, start) + newStr + soure.slice(start);
}
var n = 0;
tempArr.forEach((item, index) => {
if (index%2 === 1) {
str = insertStr(str, item+1+n, '<br>')
n+=4;
}
if (index%2 === 0 && index > 0) {
str = insertStr(str, item+n, '<br>');
n+=4;
}
});
console.log(str);// "#张三#<br>我这里有物资<br>#李四#<br>前方有敌人<br>#王五#<br>不要怂,一起上"
JS 字符串中井号固定位置添加换行符
最新推荐文章于 2026-06-08 09:55:48 发布
本文介绍了一种使用JavaScript处理字符串的特殊技巧,通过定位特定字符并插入换行符来改善阅读体验,同时展示了如何遍历字符串中特定标记的位置。

2万+

被折叠的 条评论
为什么被折叠?



