0

I am using this regex string to find all periods and exclamation and question marks that have white space around them or are not part of decimals:

/\.(?=\s|$)|\?(?=\s|$)|\!(?=\s|$)/g

I’m using mark.js to highlight this RegEx string. How can I modify this string (or use another one) that won’t highlight a question mark that comes immediately after a bracket, or [?

Here is my code:

function Highlight() {
var instance = new Mark(document.getElementById("example"));

instance.unmark();
instance.markRegExp(/\.(?=\s|$)|\?(?=\s|$)|\!(?=\s|$)/g);

}

window.onload = Highlight();
mark {
    background: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.11.1/mark.min.js"></script>
<div id="example">
<p>This is an example paragraph. I would like all the periods to be highlighted. Woohoo! This works very well! Yay! Alright, onto question marks. This is demo2. [? flagged ?] 5.5 is a number. 0.3374 is another number. Does this work?</p>
</div>

Mark.js also has an unmark() method to unmark things, but I don’t know how to use RegEx with unmark(). Help is much appreciated.

Barmar
  • 741,623
  • 53
  • 500
  • 612
Daniel
  • 25
  • 4

1 Answers1

1

Negative lookbehind (?<!\[) is inserted before \? to regex which means that the regex will take the ? whose preceding character is not [. You can add any other characters inside the negative lookbehind set to exclude ? with other preceding characters.

Warning : This is not supported in all browsers.

Alternative solution would be to use normal negate set [^\[] before ? like this /\.(?=\s|$)|[^\[]\?(?=\s|$)|\!(?=\s|$)/g. But this regex selects the preceding character as well. You have to handle it in your code.

function Highlight() {
var instance = new Mark(document.getElementById("example"));

instance.unmark();
instance.markRegExp(/\.(?=\s|$)|(?<!\[)\?(?=\s|$)|\!(?=\s|$)/g);

}

window.onload = Highlight();
mark {
    background: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.11.1/mark.min.js"></script>
<div id="example">
<p>This is an example paragraph. I would like all the periods to be highlighted. Woohoo! This works very well! Yay! Alright, onto question marks. This is demo2. [? flagged ?] 5.5 is a number. 0.3374 is another number. Does this work?</p>
</div>
sachin
  • 777
  • 5
  • 10