/([\s,]\s*world\s*,?)/i
[\s,]
let's us either have a space or a comma to ensure there is a separation between the words. Then following it with \s*
allows for zero to many white spaces between the comma/space and the word world
. We then follow that up with some more \s*
before the ,?
which means one or none commas. Then we capture ()
it with a case insensitive, i
, regular expression.
This should handle the replacing.
<style>
.highlighted {
background-color: rgb(100,100,255);
color: white;
}
</style>
<div id = "0">
"hello world"
<br>
"hello,world"
<br>
"hello world,"
<br>
",hello world"
<br>
",hello,world,"
<br>
", hello , world ,"
</div>
<div id="1"></div>
<script>
var content = document.getElementById("0").innerHTML.split("<br>"),
result = [];
for(var i in content) {
// First extract what we want.
var world = /([\s,]\s*world\s*,?)/.exec(content[i])[1],
// Split everything up to make the insertion easier.
hello = content[i].split(world);
// Place the result back.
result.push(hello.join('<span class="highlighted">'+world+'</span>'));
}
document.getElementById("1").innerHTML = result.join("<br>");
</script>
UPDATE To fit what @jsem asked down in the comments, I created a function that will determine the correct phrase, such as "hello world" or the many others based off of the search and punctuation.
function separate(search, punc) {
if(typeof punc !== "string") punc = ",";
var phrase = new RegExp(".*?(\\w+)\\s*(?:"+punc+"|\\s)\\s*(\\w+)\\s*(?:"+punc+")?","i").exec(search);
if(!phrase) throw new Error("Search passed could not be parsed.");
return {word1:phrase[1], word2:phrase[2]};
};
Then used the information gathered from that to create a unique regular expression that will grab the information to be highlighted.
function build_regex(phrase, punc) {
if(typeof punc !== "string") punc = ",";
return new RegExp("^.*?"+phrase.word1+"\\s*((?:"+punc+"|\\s)\\s*"+phrase.word2+"\\s*(?:"+punc+")?).*$", "i");
};
With these two functions, I created a highlighting function using the same splitting and joining algorithm as before.
function highlight(sentence, search, punc) {
if(typeof punc !== "string") punc = ",";
var highlighted = build_regex(separate(search, punc), punc).exec(sentence)[1],
remains = sentence.split(highlighted);
return remains.join('<span class="highlighted">'+highlighted+'</span>');
};
Ex:
highlight("This is my sentence hello, world!", "hello world");
/* Output: This is my sentence hello<span class="highlighted">, world</span>!*/
highlight("Change things up... sir.", "up sir", "\\.\\.\\.");
/* Output: Change things up<span class="highlighted">... sir</span>.*/
highlight("Give me some options? ummm...", "options! ummm", "\\?|\\!");
/* Output: Give me some options<span class="highlighted">? ummm</span>...*/