0

I am getting one string and one array of strings from api, for example as below. (These string and array is dynamic)

samplestring = "You've gotta dance like there's nobody watching, Love like you'll never be hurt, Sing like there's nobody listening, And live like it's heaven on earth.";

samplearray = dance,love,sing (The count is also dynamic)

I want to highlight the strings from samplearray if they are in samplestring,

Something Like

enter image description here

is there anyway to achieve this by css or js?

I saw this question but I can not use this because my string is dynamic. I saw this question also, but I am not sure how to implement.

J M
  • 396
  • 6
  • 23
  • what kind of style do you want? all styles should be same? – wangdev87 Nov 16 '20 at 14:46
  • "I want this thing. Can I do this thing?" are indicators of too broad questions – Taplar Nov 16 '20 at 14:47
  • Also there's not a dynamic string. A string is a string. Somewhere you're calling an API and getting a string in the response. Somewhere else you take your string and put it in your DOM. – netizen Nov 16 '20 at 14:50
  • You can loop over the array and wrap each word that you find with a span tag. Something like [this](https://jsfiddle.net/qp6bv0L8/) – Reyno Nov 16 '20 at 14:51
  • See also [How do you highlight all the words on the page that match an array of words?](https://stackoverflow.com/q/6987328/215552), [How to compare string with array of words and highlight words in string that match?](https://stackoverflow.com/q/46123744/215552), ... this question is asked multiple times a month on Stack Overflow. – Heretic Monkey Nov 16 '20 at 14:53

1 Answers1

1

You can search every words and replace the source string with the tags. Set it using innerHTML

var samplestring = "You've gotta dance like there's nobody watching, Love like you'll never be hurt, Sing like there's nobody listening, And live like it's heaven on earth.";

const samplearray = ["dance","Love","Sing"]

samplearray.forEach(str => {
  samplestring = samplestring.replaceAll(str, `<span>${str}</span>`)
})

root.innerHTML = samplestring
span {
  color: red
}
<div id="root"></div>
wangdev87
  • 8,611
  • 3
  • 8
  • 31
  • Although this work, this won't work if the word starts the same. e.g a list of allergens in ingredients string. if you have wheat and wheatflour, that code will only highlight wheat even though wheatflour will still be in samplearray. – ConfusedDev Sep 06 '22 at 09:09