Pierre-Louis Ollivier
Pierre-Louis Ollivier

Reputation: 43

First occurence of a word in a text with JavaScript Regex

I have a text where there are 6 occurrences of "Marine".

I want to find in this text the first occurrence of the word only and replace it by "Plane" for example.

I tried with this RegEx:

var myRegEx = new RegExp("^(.*)Marine(.*)$","gmi");

But it gives me the 4th, 5th, 6th occurrences...

Upvotes: 0

Views: 44

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174874

I want to find in this text the first occurrence of the word only and replace it by "Plane" for example.

var myRegEx = new RegExp("Marine","i");

or

\\b word boundary helps to do a exact match.

var myRegEx = new RegExp("\\bMarine\\b","i");

or

str.replace(/\bmarine\b/i)

Upvotes: 1

Jagdish Idhate
Jagdish Idhate

Reputation: 7742

You can do it without regex also

"Marine Marine Marine Marine Marine Marine".replace('Marine','Plane')
//"Plane Marine Marine Marine Marine Marine"

Upvotes: 3

Related Questions