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

Cha*_*ung 8 javascript string

假设我有一个变量,字符串的长度不固定,有时像

var a = "xxxxxxxxhelloxxxxxxxx";
Run Code Online (Sandbox Code Playgroud)

有时喜欢

var a = "xxxxhelloxxxx";
Run Code Online (Sandbox Code Playgroud)

我不能使用"world"因为位置不一样.

如何在字符串中找到字符串"hello"并在"hello"之后插入字符串"world"?(欢迎使用JavaScript或jQuery中的方法)

谢谢

gio*_*_13 20

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;
Run Code Online (Sandbox Code Playgroud)
<p>With regex: <strong id="regex"></strong></p>
<p>With string: <strong id="string"></strong></p>
Run Code Online (Sandbox Code Playgroud)

  • Replace返回一个新字符串,因此您需要将其分配回一个 (3认同)

Dom*_*nes 5

这将代替第一次出现

a = a.replace("hello", "helloworld");
Run Code Online (Sandbox Code Playgroud)

如果需要替换所有出现的内容,则需要一个正则表达式。(g末尾的标志表示“全局”,因此它将查找所有出现的事件。)

a = a.replace(/hello/g, "helloworld");
Run Code Online (Sandbox Code Playgroud)

  • +1只会替换第一个找到的实例。 (2认同)

Guf*_*ffa 5

这将取代第一次出现的情况:

a = a.replace("hello", "hello world");
Run Code Online (Sandbox Code Playgroud)

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

a = a.replace(/hello/g, "hello world");
Run Code Online (Sandbox Code Playgroud)


Bob*_*ein 5

以下是避免重复该模式的两种方法:

 a_new = a.replace(/hello/, '$& world');   // "xxxxxxxxhello worldxxxxxxxx"
Run Code Online (Sandbox Code Playgroud)

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

a_new = a.replace(/hello/, function (match) { 
    return match + ' world'; 
});
Run Code Online (Sandbox Code Playgroud)

替换函数传递与整个模式匹配的相同子字符串。