0

Im getting objects from a backend with a search request. Now i want to highlight the searched term when i display my object.

For example if my search term is "mirr" and in my object there is a name field called mirror

{name: "mirror"}

i want to wrap something like <span class="text-red-400">mirr<span>or about the searched word.

Is there anyway to achieve this without the usage of jquerys addClass function? Maybe there is some regex solution here? Sorry im not familiar with regex and its syntax...

I already tried it with something like myObject.replace(searchQuery, "<span class='text-red-400'>" + searchQuery + "</span>") but its not working.

If this is not working with tailwind im also open for css solutions as well.

Edit: I get some results with the following solution:

  hightlight(){
  let template = this.$refs.myComponent.outerHTML
  template = template.replace(
    new RegExp(this.query, 'gi'),
    (match) => `<span class="myClass">${match}</span>`
  )
  this.$refs.myComponent.innerHTML= template
  }

but the problem with this solution is, that also the html tags get replaced. For example if i search for "spa", then also my elements get replaced. I want to exclude every html from the replacing. For example if i want to search for "sparta" and i actually type in "spa" in my search, this should be the result <span><span class="myClass">spa</span>rta</span>

Alex
  • 132
  • 1
  • 4
  • 21
  • Does this answer your question? [How can I dynamically highlight strings on a web page?](https://stackoverflow.com/questions/32166803/how-can-i-dynamically-highlight-strings-on-a-web-page) – tauzN Apr 15 '21 at 18:36
  • How are you rendering the search query? If the renderer escapes HTML this might not work as you expect – T J Apr 15 '21 at 21:09
  • Unfortunalty not. First of all i dont get any result out of this, no highlighting. Also i dont want to search the whole document for my given string, only the text in my actual component. I also tried something like `let template = this.$refs.myComponent.innerHTML template = template.replace( new RegExp(this.query, 'gi'), (match) => ${match} ) this.$refs.myComponent.innerHTML= template` this gives me a highlighted result, but its some weird result because every html tag also gets replaces (e.g. i search for "sp" every span – Alex Apr 16 '21 at 09:19
  • *every span gets replaced... Maybe there is another regex solution here, to esape every HTML element like and so on. – Alex Apr 16 '21 at 09:21
  • So what i am looking for example is, a regex which replace my text in innerhtml, but ONLY text which is not part of a html tag element. For example if i search for "spa" i dont want to replace "" elements, but for example the word "sparta" inside some span element. But not the span element itself. :) – Alex Apr 16 '21 at 09:28

0 Answers0