How do I ignore certain characters when replacing certain words in javascript?

Viewed 24

I want the second window to display the sentence "I like apple and banana, and orange and maybe even pears?" with also "Banana" and "pears" highlighted in red, that is ignoring the fact that the comma or question mark follows the words. Is there any way to do this without adding items to the array such as "banana," or "pears?"

const heroes = [" banana ", " pears ", " apple ", " orange "];

var regexFromMyArray = new RegExp(heroes.join("|"), 'ig');

$('#board').keyup(function(event){
  document.getElementById('dummy').innerHTML = $('#board').html().replace(regexFromMyArray,function(str){
    return '<span class="highlighted">'+str+'</span>'
  })
})

var target = $("#dummy");
$("#board").scroll(function() {
  target.prop("scrollTop", this.scrollTop)
    .prop("scrollLeft", this.scrollLeft);
});
.color-red{
    color: #F00;
}

.original {
   position:static;
    width: 70%;
    margin: 0 auto;
    padding: 1em;
    background: #fff;
    color: #000;
    height:100px;
    margin:2px;
    border:1px solid black;
    color:#fff;
    overflow:auto;
}

#dummy{
  color:black;
}
#board{
  z-index:11;
  background:transparent;
   color:black;
    caret-color: black;
}
.original span.highlighted {
    color:red;
}

#kommentarer{
  z-index:11;
  background:transparent;
   color:black;
    caret-color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<h3>Search text for fruits</h3>

<br>

<p>I want the second window to display the sentence "I like apple and banana, and orange and maybe even pears?" with "Banana" and "pears" highlighted in red, that is ignoring the fact that the comma or question mark follow the words</p></p>

<br>
<br>

<p>Paste in the sentence here:</p>
<div id="board" class="original" contenteditable="true">

</div>

<br>
<br>

<p>The fruits are displayed in red:</p>
<div id="dummy" class="original">

</div>
<br>
<br>


</div>

1 Answers

Two things to change:

  • Remove the spaces around the search words
  • Add word-breaks in the regex pattern: \b

So:

const heroes = ["banana", "pears", "apple", "orange"];

var regexFromMyArray = new RegExp("\\b(" + heroes.join("|") + ")\\b", 'ig');
Related