55

I was wondering how to use a regexp to match a phrase that comes after a certain match. Like:

var phrase = "yesthisismyphrase=thisiswhatIwantmatched";
var match = /phrase=.*/;

That will match from the phrase= to the end of the string, but is it possible to get everything after the phrase= without having to modify a string?

DVK
  • 126,886
  • 32
  • 213
  • 327
bryan sammon
  • 7,161
  • 15
  • 38
  • 48

5 Answers5

80

You use capture groups (denoted by parenthesis).

When you execute the regex via match or exec function, the return an array consisting of the substrings captured by capture groups. You can then access what got captured via that array. E.g.:

var phrase = "yesthisismyphrase=thisiswhatIwantmatched"; 
var myRegexp = /phrase=(.*)/;
var match = myRegexp.exec(phrase);
alert(match[1]);

or

var arr = phrase.match(/phrase=(.*)/);
if (arr != null) { // Did it match?
    alert(arr[1]);
}
Community
  • 1
  • 1
DVK
  • 126,886
  • 32
  • 213
  • 327
18
phrase.match(/phrase=(.*)/)[1]

returns

"thisiswhatIwantmatched"

The brackets specify a so-called capture group. Contents of capture groups get put into the resulting array, starting from 1 (0 is the whole match).

thejh
  • 44,854
  • 16
  • 96
  • 107
  • 4
    It is important to realize the `.match` returns `null` if the match fails, so test for that before trying to get the first index is a good idea. Also, if you have more than one phase in that key=value string you might change the regex to `/phrase=(.*?)(;|$)/` where ; is the delimiter. Further, you could abstract this with a method using the RegEx constructor... – Hemlock Dec 31 '10 at 18:04
6

It is not so hard, Just assume your context is :

const context = "https://example.com/pa/GIx89GdmkABJEAAA+AAAA";

And we wanna have the pattern after pa/, so use this code:

const pattern = context.match(/pa\/(.*)/)[1];

The first item include pa/, but for the grouping second item is without pa/, you can use each what you want.

AmerllicA
  • 29,059
  • 15
  • 130
  • 154
0

Let try this, I hope it work

var p = /\b([\w|\W]+)\1+(\=)([\w|\W]+)\1+\b/;
console.log(p.test('case1 or AA=AA ilkjoi'));
console.log(p.test('case2 or AA=AB'));
console.log(p.test('case3 or 12=14'));
Bao Mai
  • 3
  • 3
0

If you want to get value after the regex excluding the test phrase, use this: /(?:phrase=)(.*)/

the result will be

0: "phrase=thisiswhatIwantmatched" //full match
1: "thisiswhatIwantmatched" //matching group
Alexey Nikonov
  • 4,958
  • 5
  • 39
  • 66