20

Suppose I have string variable such as:

var a = "xxxxxxxxhelloxxxxxxxx";

or:

var a = "xxxxhelloxxxx";

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

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

6 Answers 6

34

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>

Sign up to request clarification or add additional context in comments.

2 Comments

Replace returns a new string, so you'll need to assign it back to a
This method is genious!!. It actually removes the "hello" string. That is why in the second parameter inside a function written a "hello world" instead of " world".
10

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");

Comments

5

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");

1 Comment

@user2072826: Thanks for spotting that.
5

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.

Comments

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

Maybe.

Comments

2

You can use replace, would be much easier than indexOf

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.