Charles Yeung
Charles Yeung

Reputation: 38803

Finding a substring and inserting another string

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?

Upvotes: 20

Views: 22694

Answers (6)

Bob Stein
Bob Stein

Reputation: 17224

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.

Upvotes: 5

gion_13
gion_13

Reputation: 41533

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>

Upvotes: 34

Guffa
Guffa

Reputation: 700372

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

Upvotes: 5

Dominic Barnes
Dominic Barnes

Reputation: 28429

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

Upvotes: 10

Jason Jong
Jason Jong

Reputation: 4330

You can use replace, would be much easier than indexOf

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

Upvotes: 2

Marty
Marty

Reputation: 39456

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.

Upvotes: 3

Related Questions