Friday, 23 July 2021

Javascript regex difference between match and exec, and test, and regex to get : separated key values with comma in end from string

 difference between JS exec and match


https://stackoverflow.com/questions/9214754/what-is-the-difference-between-regexp-s-exec-function-and-string-s-match-fun


exec with a global regular expression is meant to be used in a loop, as it will still retrieve all matched subexpressions. So:

var re = /[^\/]+/g;
var match;

while (match = re.exec('/a/b/c/d')) {
    // match is now the next match, in array form.
}

// No more matches.
JS Regex Test

https://www.w3schools.com/jsref/jsref_regexp_test.asp

The test() method tests for a match in a string.

This method returns true if it finds a match, otherwise it returns false.


Search a string for the character "e":

var str = "The best things in life are free";
var patt = new RegExp("e");
var res = patt.test(str);

String.match does this for you and discards the captured groups. 

Match returns an array



Regex to find : separated key value pairs with comma in the end


/((?:"[^"]*"|[^:,])*):((?:"[^"]*"|[^,])*)/gm



https://stackoverflow.com/questions/37157779/regexp-to-get-text-in-a-key-value-pair-separated-by-a-colon

No comments:

Post a Comment