假设我有字符串变量,例如:
var a = "xxxxxxxxhelloxxxxxxxx";
或:
var a = "xxxxhelloxxxx";
我想在 "hello"
之后插入 "world"
。
我不能使用 substr()
因为无法提前知道位置。我如何在 JavaScript 或 jQuery 中执行此操作?
最佳答案
var a = "xxxxhelloxxxxhelloxxxx";
a = a.replace(/hello/g,"hello world"); // if you want all the "hello"'s in the string to be replaced
document.getElementById("regex").textContent = a;
a = "xxxxhelloxxxxhelloxxxx";
a = a.replace("hello","hello world"); // if you want only the first occurrence of "hello" to be replaced
document.getElementById("string").textContent = a;
<p>With regex: <strong id="regex"></strong></p>
<p>With string: <strong id="string"></strong></p>
关于javascript - 查找子字符串并插入另一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5865257/