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

Javascript 查找子字符串并插入另一个字符串,javascript,string,Javascript,String,假设我有如下字符串变量: var a = "xxxxxxxxhelloxxxxxxxx"; 或: 我想在“hello”之后插入“world” 我不能使用substr(),因为事先不知道位置。如何在JavaScript或jQuery中实现这一点? var a=“xxxxhelloxxxxhelloxxxx”; a=a.replace(/hello/g,“hello world”);//如果要替换字符串中的所有“hello” document.getElementById(“regex”).tex

假设我有如下字符串变量:

var a = "xxxxxxxxhelloxxxxxxxx";
或:

我想在
“hello”
之后插入
“world”

我不能使用
substr()
,因为事先不知道位置。如何在JavaScript或jQuery中实现这一点?

var a=“xxxxhelloxxxxhelloxxxx”;
a=a.replace(/hello/g,“hello world”);//如果要替换字符串中的所有“hello”
document.getElementById(“regex”).textContent=a;
a=“xxxxhelloxxxxhelloxxxx”;
a=a.替换(“你好”,“你好世界”);//如果只想替换第一次出现的“hello”
document.getElementById(“字符串”).textContent=a
带有正则表达式的

带字符串:


也许吧。

这将取代第一次出现

a = a.replace("hello", "helloworld");
如果需要替换所有引用,则需要正则表达式。(末尾的
g
标志表示“全局”,因此它将查找所有发生的事件。)


您可以使用replace,这比indexOf容易得多

var newstring = a.replace("hello", "hello world");

这将取代第一种情况:

a = a.replace("hello", "hello world");
如果需要替换所有事件,请使用正则表达式进行匹配,并使用全局(g)标志:

这里有两种方法可以创建该模式:

 a_new = a.replace(/hello/, '$& world');   // "xxxxxxxxhello worldxxxxxxxx"
$&
表示与整个模式匹配的子字符串。它是一个用于替换字符串的字符串

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

A被传递给与整个模式匹配的相同子字符串。

Replace返回一个新字符串,因此您需要将其分配回A。该方法是genious!!。它实际上删除了“hello”字符串。这就是为什么在函数中的第二个参数中写了一个“helloworld”而不是“world”。@user2072826:谢谢你发现了这一点。
a = a.replace("hello", "hello world");
a = a.replace(/hello/g, "hello world");
 a_new = a.replace(/hello/, '$& world');   // "xxxxxxxxhello worldxxxxxxxx"
a_new = a.replace(/hello/, function (match) { 
    return match + ' world'; 
});