-2

I have a string like:

some people may work for some thing new.

I need to fetch the 2nd instance of the word 'some' using javascript reg exp.

how can i get that?

here is my try:

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

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

console.log(patt);

But I am getting simply 'true' in console. But I need to get the word to be consoled. ( even i may need to replace too).

any one help me?

3gwebtrain
  • 14,640
  • 25
  • 121
  • 247

5 Answers5

1

You need to use .match with the regex, and also use the g flag for global

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

Will give you an array of all instances of the word some

Patrick Evans
  • 41,991
  • 6
  • 74
  • 87
1
var text = "some people may work for some thing new";

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

console.log(patt);

will give you all the instances of the word you want to find in the sentence. Then you can simply use replace similarly.

Suppose you want to search and replace the second word some. Then just see this question

In addition to that you can also do something like 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");
Community
  • 1
  • 1
aelor
  • 10,892
  • 3
  • 32
  • 48
0

You can use the match method of the string to get an array of all the occurrences:

text.match(/some/g)

You need the 'g' flag in the regex otherwise the match will stop after the first hit

codebox
  • 19,927
  • 9
  • 63
  • 81
0

Here is how you replace the 2nd instance:

'some people may work for some thing new.'.replace(/(\bsome\b.*?)\bsome\b/, "$1foo");
//=> some people may work for foo thing new.
anubhava
  • 761,203
  • 64
  • 569
  • 643
0

use the function exec(text) instend of test(text)

replace your code:

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

to:

var patt = /some/.exec(text);
st mnmn
  • 3,555
  • 3
  • 25
  • 32