Jegadeesan Jegadeesan - 1 year ago 61
Javascript Question

how to slice the text before after a particular word using JavaScript

I'm getting the div's html value using JavaScript. it returns the value like

From looking down the Line, he turned himself about again, and, raising his eyes, saw my figure high above him.Without prolonging the narrative to dwell on any one of its curious circumstances more than on any other, I may, in closing it, point out the coincidence that the warning of the Engine-Driver included, not only the words which the unfortunate Signal-man had repeated to me as haunting him, but also the words which I myself—not he—had attached, and that only in my own mind, to the gesticulation he had imitated.


I need to slice the value before and after a particular text.unfortunate is that particular word. For eg, i need to get like below

....Engine-Driver included, not only the words which the unfortunate Signal-man had repeated to me as haunting him, but also the words which I myself....

Answer Source

Based on the updated comments, you need to highlight the word so you can use .replace() with a simple regex like

$('div').html(function(_, html){
    return html.replace(/(unfortunate)/gi, '<b>$1</b>')
})

Demo: Fiddle

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download