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
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];
Thank you. Can I also use regex modifiers in Javascript ? For example to perform case-insensitive or multiline search etc.
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];
Share on FacebookShare on TwitterShare on LinkedInSend email
3 answers
x
x
2024 AnswerTabsTermsContact us