Question

I have this sample text, which is retrieved from the class name on an 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 match the "test1"/"test2" data in each of these examples. I am currently using the following regex, which matches the "err-test1" type of word. I can't figure out how to limit it to just the data after the hyphen(-).

/err-(\S*)/ig

Head hurts from banging against this wall.

Was it helpful?

Solution

From what I am reading, your code already works.

Regex.exec() returns an array of results on success.

The first element in the array (index 0) returns the entire string, after which all () enclosed elements are pushed 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

OTHER TIPS

You could try 'err-([^ \n\r]*)' - but are you sure that it is the regex that is the problem? Are you using the whole result, not just the first capture?

The stuff after the - should be in the results array. The first item is all the matching text (e.g. "err-test1") and the next items are the matches from the capture parentheses (e.g. "test1").

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

Here's a reference site.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top