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

17
假设我有一个字符串变量,如下所示:
var a = "xxxxxxxxhelloxxxxxxxx";

或者:

var a = "xxxxhelloxxxx";

我想在"hello"后面插入"world"

由于位置事先未知,因此无法使用substr()。请问如何在JavaScript或jQuery中实现这一点?

6个回答

33

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>


3
"Replace"会返回一个新的字符串,因此您需要将其赋值回去。 - Matt Greer
这个方法真是太聪明了!!它实际上删除了“hello”字符串。这就是为什么在函数的第二个参数中写了一个“hello world”而不是“world”。 - Marfin. F

8
这将替换第一个出现的内容。
a = a.replace("hello", "helloworld");

如果您需要替换所有出现的内容,您需要使用正则表达式。(在末尾加上g标志意味着“全局”,因此它将找到所有出现的内容。)
a = a.replace(/hello/g, "helloworld");

5

这里有两种避免重复这个模式的方法:

 a_new = a.replace(/hello/, '$& world');   // "xxxxxxxxhello worldxxxxxxxx"

$& 代表与整个模式匹配的子字符串。它是替换字符串中使用的特殊代码

a_new = a.replace(/hello/, function (match) { 
    return match + ' world'; 
});

一个替换函数会得到与整个模式匹配的相同子字符串。


5
这将替换第一个出现的内容:
a = a.replace("hello", "hello world");

如果你需要替换所有出现的内容,你可以使用正则表达式进行匹配,并使用全局(g)标志:

a = a.replace(/hello/g, "hello world");

@user2072826:感谢您发现了这个问题。 - Guffa

3
var find = "hello";

var a = "xxxxxxxxxxxxxhelloxxxxxxxxxxxxxxxx";
var i = a.indexOf(find);

var result = a.substr(0, i+find.length) + "world" + a.substr(i+find.length);

alert(result); //xxxxxxxxxxxxxhelloworldxxxxxxxxxxxxxxxx

也许。

2
您可以使用replace,这比indexOf更容易。
var newstring = a.replace("hello", "hello world");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接