How to get text with preg_match and Regex in Javascript ?

I need to extract text value like I usually do with preg_match() in PHP. But now I need to do it in Javascript. Can you please give me advice and example how to make it work ?
0
give a positive ratinggive a negative rating
25 Jun 2019 at 07:02 PM
Hi,

The similar function to preg_match() in Javascript is exec(). It can be used to find a match or extract the specific text from string, according to regex pattern condition.

In this example, the function will extract the text between <ABC></ABC> tags:

var string = '<\ABC>The content<\/\ABC>';
var pattern = /<\ABC>(.*)<\/\ABC>/;
var text = pattern.exec(string)[1];
0
give a positive ratinggive a negative rating
03 Jul 2019 at 07:31 PM
Tim
Thank you. Can I also use regex modifiers in Javascript ? For example to perform case-insensitive or multiline search etc.
0
give a positive ratinggive a negative rating
04 Jul 2019 at 06:15 PM
Yes, the modifiers can be used, when needed. For example you can use:

g - to find all matches, rather than stopping after the first match

m - to multiline matching

i - to case insensitive matching

The code with regex modifiers will look like:

var string = '<\ABC>The content<\/\ABC>';
var pattern = /<\ABC>(.*)<\/\ABC>/im;
var text = pattern.exec(string)[1];
0
give a positive ratinggive a negative rating
08 Jul 2019 at 07:08 PM
Tim
Share on FacebookShare on TwitterShare on LinkedInSend email
x
x
2024 AnswerTabsTermsContact us