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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5865257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 18:37:17  来源:igfitidea点击:

Finding a substring and inserting another string

javascriptstring

提问by Charles Yeung

Suppose I have string variable such as:

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

var a = "xxxxxxxxhelloxxxxxxxx";

or:

或者:

var a = "xxxxhelloxxxx";

I want to insert "world"after "hello".

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

I can't use substr()because the position is not known ahead of time. How can I do this in JavaScript or jQuery?

我无法使用,substr()因为位置不知道提前。我怎样才能在 JavaScript 或 jQuery 中做到这一点?

回答by gion_13

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>

回答by Dominic Barnes

This will replace the first occurrence

这将替换第一次出现

a = a.replace("hello", "helloworld");

If you need to replace all of the occurrences, you'll need a regular expression. (The gflag at the end means "global", so it will find all occurences.)

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

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

回答by Guffa

This will replace the first occurance:

这将取代第一次出现:

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

If you need to replace all occurances, you use a regular expression for the match, and use the global (g) flag:

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

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

回答by Bob Stein

Here's a way that avoids repeating the "hello" pattern:

这是一种避免重复“hello”模式的方法:

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

$&refers to the substring that matched the whole pattern. It is one of several special $ codesfor the replacement string.

$&指匹配整个模式的子串。它是替换字符串的几个特殊 $ 代码之一。

Here's another way to get the same result with a replacer function:

这是使用替换函数获得相同结果的另一种方法:

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

回答by Marty

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

Maybe.

或许。

回答by Jason Jong

You can use replace, would be much easier than indexOf

您可以使用替换,会比 indexOf 容易得多

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