[英]First occurence of a word in a text with JavaScript Regex
I have a text where there are 6 occurrences of "Marine". 我有一个文本,其中出现了6个“海洋”事件。
I want to find in this text the first occurrence of the word only and replace it by "Plane" for example. 我想在此文本中仅找到该词的首次出现,并以“ Plane”代替。
I tried with this RegEx: 我尝试使用此RegEx:
var myRegEx = new RegExp("^(.*)Marine(.*)$","gmi");
But it gives me the 4th, 5th, 6th occurrences... 但这给了我第四,第五,第六次出现...
You can do it without regex
also 您也可以不使用regex
"Marine Marine Marine Marine Marine Marine".replace('Marine','Plane')
//"Plane Marine Marine Marine Marine Marine"
I want to find in this text the first occurrence of the word only and replace it by "Plane" for example. 我想在此文本中仅找到该词的首次出现,并以“ Plane”代替。
var myRegEx = new RegExp("Marine","i");
or 要么
\\\\b
word boundary helps to do a exact match. \\\\b
单词边界有助于精确匹配。
var myRegEx = new RegExp("\\bMarine\\b","i");
or 要么
str.replace(/\bmarine\b/i)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.