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 ?
25 Jun 2019 at 07:02 PM
0pnshow more
onefiveonefive
Find us on Facebook AnswertabsFind us on Facebook Answertabs
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];
03 Jul 2019 at 07:31 PM
0pnshow more
TimTim
Thank you. Can I also use regex modifiers in Javascript ? For example to perform case-insensitive or multiline search etc.
04 Jul 2019 at 06:15 PM
0pnshow more
onefiveonefive
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];
08 Jul 2019 at 07:08 PM
0pnshow more
TimTim
share on facebookshare on twitter
2021 AnswerTabsTermsContact us