user1575921 user1575921 - 6 months ago 8
Javascript Question

break, if following string is <div>

I want to find string after

#
, I have a problem if
#a
or
#a&nbsp;<div>..

are both working to return
a
, but if
#a<div>..
will return
a<div>
.

how to avoid if following string is
<div>
or
<br>
or
<p>
than just break,
e.g

#a<div>bc
-
a


https://regex101.com/r/xD1vN0/1

var re = /#([^#\s]*)/g;

Answer

You can use a regex with a tempered greedy token:

/#((?:(?!<(?:div|br|p)>)[^#\s])*)/g

The (?:(?!<(?:div|br|p)>)[^#\s])* is a tempered greedy token that matches any character other than # and whitespace that do not start a sequence of either <div>, <br>, or <p>.

JS demo:

var re = /#((?:(?!<(?:div|br|p)>)[^#\s])*)/g; 
var str = `#a<div>
#b<br>
#c<p>
#d<hi>`;
var res = [];
 
while ((m = re.exec(str)) !== null) {
    res.push(m[1]);
}
document.body.innerHTML = "<pre>" + JSON.stringify(res.map(x => x.replace(/</g,"&lt;").replace(/</g,"&gt;")), 0, 4) + "</pre>";

Comments