Finding a substring and inserting another string

Suppose I have a variable, the string length is not fixed, sometimes like

var a = xxxxxxxxhelloxxxxxxxx;

sometimes like

var a = xxxxhelloxxxx;

I canโ€™t use substr()because the position is not identical.

How can I find the string "hello" in the string and insert the string "world" after "hello"? (method in JavaScript or jQuery is welcome)

thank

+5
source share
5 answers

var a = "xxxxhelloxxxxhelloxxxx";
a = a.replace(/hello/g,"hello world"); // if you want all the "hello" 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>
Run codeHide result
+15
source

This will replace the first occurrence.

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

If you need to replace all occurrences, you will need a regular expression. (The flag gat the end means global, so it will find all occurrences.)

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

:

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

, (g):

a = a.replace(/hello/g, "hello world");
+3
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

.

+1
source

You can use replace, it would be much simpler than indexOf

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

All Articles