假设我有一个变量,字符串的长度不固定,有时像
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)
这将代替第一次出现
a = a.replace("hello", "helloworld");
Run Code Online (Sandbox Code Playgroud)
如果需要替换所有出现的内容,则需要一个正则表达式。(g末尾的标志表示“全局”,因此它将查找所有出现的事件。)
a = a.replace(/hello/g, "helloworld");
Run Code Online (Sandbox Code Playgroud)
这将取代第一次出现的情况:
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)
以下是避免重复该模式的两种方法:
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)
替换函数传递与整个模式匹配的相同子字符串。
| 归档时间: |
|
| 查看次数: |
13202 次 |
| 最近记录: |