Reg Expression - 在javascript中如何获得第二个实例?

时间:2014-03-26 09:00:24

标签: javascript regex

我有一个字符串:

some people may work for some thing new.

我需要获取单词的第二个实例' some'使用javascript reg exp。

我怎么能得到它?

这是我的尝试:

var text = "some people may work for some thing new";

var patt = /some/.test(text);

console.log(patt);

但我变得简单'真实'在控制台。但我需要让这个词得到安慰。 (即使我可能也需要更换)。

任何人帮助我?

5 个答案:

答案 0 :(得分:1)

您需要将.match与正则表达式一起使用,并将g标志用于全局

var text = "some people may work for some thing new";
var patt = /some/g;
var matches = text.match(patt);
console.log( matches );
console.log( matches[1] );

将为您提供单词some

的所有实例的数组

答案 1 :(得分:1)

var text = "some people may work for some thing new";

var patt = text.match(/some/g);

console.log(patt);

将为您提供您希望在句子中找到的单词的所有实例。 然后你可以简单地使用替换。

假设您要搜索并替换第二个单词some。 然后,只需查看this问题

除此之外,您还可以执行以下操作:

function doit(str, tobereplaced, occurence, withwhat){

var res = str.split(tobereplaced);
console.log(res);
var foo = []
for (var i = 0; i < occurence; i++) {
   foo.push(res[i]);
}

var bar = []
for (var j = occurence; j < res.length; j++) {
   bar.push(res[i]);
}

return foo.join("")+withwhat+bar.join("");
}

var str = "ssfds some people may work for some thing new some thing again some again";
doit(str, "some", 2, "bomb");

答案 2 :(得分:0)

您可以使用字符串的match方法获取所有匹配项的数组:

text.match(/some/g)

你需要正则表达式中的'g'标志,否则匹配将在第一次击中后停止

答案 3 :(得分:0)

以下是替换第二个实例的方法:

'some people may work for some thing new.'.replace(/(\bsome\b.*?)\bsome\b/, "$1foo");
//=> some people may work for foo thing new.

答案 4 :(得分:0)

使用函数exec(text)代替test(text)

替换你的代码:

var patt = /some/.test(text);

为:

var patt = /some/.exec(text);