Javascript regex help

I have this sample text, which is retrieved from the class name in the html element:

rich-message err-test1 erroractive
rich-message err-test2 erroractive
rich-message erroractive err-test1
err-test2 rich-message erroractive

      

I am trying to map data "test1" / "test2" in each of these examples. I am currently using the following regex which matches the word type "err-test1". I can't figure out how to limit it to only the data after the hyphen (-).

/err-(\S*)/ig

      

My head hurts from hitting this wall.

+1


source to share


3 answers


From what I read, your code is already working.

Regex.exec()

returns an array of results on success.



The first element of an array (index 0) returns the entire string, after which all ()

nested elements are inserted into this array.

var string = 'rich-message err-test1 erroractive';
var regex = new RegExp('err-(\S*)', 'ig');
var result = regex.exec(string);

alert(result[0]) --> returns err-test1
alert(result[1]) --> returns test1

      

+3


source


You can try "err - ([^ \ n \ r] *)" - but are you sure this is a regex problem? Are you using the entire result, not just the first capture?



0


source


Material after - must be in the results array. The first element is all matching text (for example, "err-test1"), and the following elements are matches from the capturing brackets (for example, "test1").

myregex = /err-(\S*)/ig;
mymatch = myregex.exec("data with matches in it");
testnum = mymatch[1];

      

Here's the reference site .

0


source







All Articles