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 ?
posted on 25.06.2019 at 19:02
0pnshow more
onefiveonefive
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];
posted on 03.07.2019 at 19:31
0pnshow more
TimTim
Thank you. Can I also use regex modifiers in Javascript ? For example to perform case-insensitive or multiline search etc.
posted on 04.07.2019 at 18:15
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];
posted on 08.07.2019 at 19:08
0pnshow more
TimTim
share on facebookshare on twitter
2020 AnswerTabsTermsContact us
This site uses cookies to improve your experience, for analytics and ads. By continuing to browse this site you agree to our use of cookies.