How do I use regex in JavaScript to capture the text between two particular characters? -
How do I use regex in JavaScript to capture the text between two particular characters? -
in illustration below trying capture text between 2 asterixes.
var str="the *rain in spain* stays in plain"; var patt1=/\*...\*/; console.log(str.match(patt1)); i'm trying follow illustration here
http://www.regular-expressions.info/examples.html
\q...\e matches characters between \q , \e literally, suppressing meaning of special characters.
but having problem next along
try
var str="the *rain in spain* stays in plain"; var patt1=/\*.*\*/; console.log(str.match(patt1)); the \* means literal "*" character. . means character , * means number of times, .* means "any number of characters".
optional bonus:
the code above should work fine, you'll notice matches greedily. input abcd*efgh*ijkl*mnop, output *efgh*ijkl*, whereas might have preferred non-greedy match *efgh*.
to this, utilize
var patt1=/\*.*?\*/; the ? operator indicates non-greediness , ensures to the lowest degree number of characters possible next \* eaten, whereas without ?, characters possible next \* eaten.
to larn more recommend http://www.regular-expressions.info/repeat.html . in particular read "laziness instead of greediness" part.
javascript regex
Comments
Post a Comment