javascript - 查找子字符串并插入另一个字符串

标签 javascript string

假设我有字符串变量,例如:

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/

相关文章:

python - 替换文件内容中的字符串

c - c中的字符串扫描

c# - 在不总是相同的字符串中间添加一个字符

javascript - 查找文本框中的总行数

javascript - 将 36 进制转为 BigInt?

javascript - 在 IF 函数内使用 REGEX

c# - 确定字符串的第一个字符是大写还是小写

javascript - 输入提交按钮在 Android 设备上不起作用

javascript - 只是想问一下Button的功能

java - 为什么不可变字符串比可变字符串更有效