Reputation: 43
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
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
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