Skip to content Skip to sidebar Skip to footer

Highlight Specific Occurrence Of Word In Text

I am trying to highlight a specific occurrence of a word in a text using jquery/js. Trying to find out if there are any existing libraries I can use. I read about mark.js but it do

Solution 1:

Just pass in the specific index of the token (character sequence you are looking for) to a function that takes the string, token, and index as parameters. You can now use the 2nd parameter of indexOf to update the beginning of where the string will be searched from using the last result:

consthighlighter = (string, token, index) => {
  let n = -1for (let i = 0; i <= index; i++) {
    n = string.indexOf(token, n + 1)
  }
  return string.slice(0, n) + string.slice(n).replace(token, '<span class="highlight">' + token + '</span>')
}

const text = 'In a home, there is a room, the room has a door.<br>'const firstRoom = highlighter(text, 'room', 0)
const secondRoom = highlighter(text, 'room', 1)

$('#result').append(firstRoom)
$('#result').append(secondRoom)
.highlight {
  background-color: lightblue;
}
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><divid="result"></div>

The -1 is important since this function would otherwise miss the first token occurence if it appears at the start of the string.

Solution 2:

You could do it like this:

let text = "In a home, there is a room, the room has a door.";
let search = "room";
var n = text.lastIndexOf(search);
text = text.slice(0, n) + text.slice(n).replace(search, "<span class='highlight'>" + search + "</span>");
$("#result").append(text);
.highlight {
  color:red;
}
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><divid="result"></div>

Solution 3:

// To replace all (commented out so it doesn't interfere with the other one)/*
var p = document.getElementById("text"); // Gets the <p>
var text = p.innerText; // Gets the text it contains
var wordToReplace = "room"; // Which word should be replaced
var newtext = text.replaceAll(wordToReplace, '<span class="highlight">' + wordToReplace + '</span>'); // Replaces the word with the word wrapped in <span> tags, so it will look highlighted
p.innerHTML = newtext; // Change it back
*/// To replace specific occurencesvar paragraph = document.getElementById("text"); // Gets the <p>var txt = paragraph.innerText; // Gets the text it containsvar textToReplace = 'room'// Word to be replacedvar replace = RegExp(textToReplace, 'g');
var matches = txt.matchAll(replace); // Gets all places where the text matches the wordvar replacementPositions = [0, 2]; // Occurences which should be highlightedvar i = 0; // Which match this is; starts at 0for (const match of matches) { // For each match...var text = match[0]; // The matching textvar start = match.index; // Start positionvar end = match.index + text.length; // End positionif (replacementPositions.includes(i)) { // If it should be replaced (in the replacementPositions array)var startText = txt.substring(0, start - 1); // Text before matchvar endText = txt.substring(start); // Text after match
    endText = endText.substring(text.length); // Removes matching text from the text after the match
    txt = startText + '<span class="highlight">' + text + '</span>' + endText; // Insert the match back in, wrapped in a <span>
  }
  i++; // Increment
}
paragraph.innerHTML = txt; // Set the paragraph text back
.highlight {
  background-color: yellow;
}
<pid="text">First: room. Another one: room. Last time: room</p>

The first method detects all occurrences of the word and wraps them in a <span>. The <span> has a style that sets the background color of the text, so it looks 'highlighted'.

The second method goes through every occurrence of the word and checks if it should be highlighted. If so, it does some operations that wrap that occurrence in a <span>, like the method above.

Post a Comment for "Highlight Specific Occurrence Of Word In Text"