Javascript Regexp - Match Characters after a certain phrase

JavascriptRegex

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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).

Solution 3 - Javascript

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.

Solution 4 - Javascript

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

Solution 5 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionbryan sammonView Question on Stackoverflow
Solution 1 - JavascriptDVKView Answer on Stackoverflow
Solution 2 - JavascriptthejhView Answer on Stackoverflow
Solution 3 - JavascriptAmerllicAView Answer on Stackoverflow
Solution 4 - JavascriptBao MaiView Answer on Stackoverflow
Solution 5 - JavascriptAlexey NikonovView Answer on Stackoverflow