嗨,我在Javascript中有一个问题,是否可以使用给定的数组,例如["old", "great", "other", "long", "good", "last"]如果你有一个var str = "oldgreatotherlonggoodlastfirstnewownlittle"并使用数组和正则表达式用空格打印它?例如。old great other long good lastfirstnewownlittle我只是在用JavaScript做一个简单的网络应用程序,只是为了练习。
3 回答

汪汪一只猫
TA贡献1898条经验 获得超8个赞
将数组转换为正则表达式,并在每次匹配之前添加一个空格。
var str = "oldgreatotherlonggoodlastfirstnewownlittle";
var newstr = str.replace(/old|great|other|long|good|last/g, " $&");
console.log(newstr);
str = "greatotherlonggoodlastfirstnewownlittleold";
newstr = str.replace(/old|great|other|long|good|last/g, " $&");
console.log(newstr);
在替换字符串中,$&
代表与正则表达式匹配的任何内容。

眼眸繁星
TA贡献1873条经验 获得超9个赞
如果您正在寻找一种从阵列中制作正则表达式的方法,则可以执行以下操作:
let words = ["old", "great", "other", "long", "good", "last"];
let reg = new RegExp(words.join("|"), "g")
然后,您可以将其string.replace用于达到理想的效果
添加回答
举报
0/150
提交
取消