开发者

Finding a substring and inserting another string

开发者 https://www.devze.com 2023-03-02 00:58 出处:网络
Suppose I have string variable such as: var a = \"xxxxxxxxhelloxxxxxxxx\"; or: var a = \"xxxxhelloxxxx\";

Suppose I have string variable such as:

var a = "xxxxxxxxhelloxxxxxxxx";

or:

var a = "xxxxhelloxxxx";

I want to insert "world" after "hel开发者_开发技巧lo".

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


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>


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 g flag at the end means "global", so it will find all occurences.)

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


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:

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


Here are two ways to avoid repeating the pattern:

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

$& represents the substring that matched the whole pattern. It is a special code for use in the replacement string.

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

A replacer function is passed the same substring that matched the whole pattern.


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.


You can use replace, would be much easier than indexOf

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

精彩评论

暂无评论...
验证码 换一张
取 消