skip to Main Content

Sentence: Wir gehen ins Kino um 19 Uhr.

Word: Kino

I have this script to make the word kino bolded:

<div id="word" hidden>{{Word}}</div>

<script>
  (() => {
const word = document.getElementById("word").innerText;
const sentenceEl = document.getElementById("sentence");
    sentenceEl.innerHTML = sentenceEl.innerHTML.replace(
      // case-insensitive regular expression
      new RegExp(word, "gi"), `<b><i><span style=' '>${word}</span></b></i>`
    );
  })();
</script>

but if Word: das Kino · Kinos · Kinos

the word kino doesn’t get bolded in the sentence, so i want to edit the code

I know nothing about programming.

2

Answers


  1. Firstly, I think that the code const word = document.getElementById("word").innerText; is wrong. We must use let word = document.getElementById("word").textContent;

    Secondly, the replace regex should be simple as this

    let sentence = document.getElementById("sentence").innerHTML;
      const regex = new RegExp(word, "gi");
      sentence = sentence.replace(regex, `<b><i>${word}</i></b>`);
      document.getElementById("sentence").innerHTML = sentence;
    

    Remember to close the html tag with right position.

    See the demo here https://codepen.io/giang-vincent/pen/eYPgKep?editors=1111

    Login or Signup to reply.
  2. Test unique changes

            <div id="word" hidden>Word</div>
            <div id="sentence">Hello Word word woRd wOrD World</div>
        <div id="sentence2"></div>
    
            <script>
              (() => {
            const word = document.getElementById("word").innerText;
        const sentenceEl = document.getElementById("sentence");
        const sentenceEl2 = document.getElementById("sentence2");
    
        sentenceEl2.innerHTML = sentenceEl.innerHTML.replace(
                  // case-insensitive regular expression
                  new RegExp(word, "g"), `<b><span style=' '>${word}</span></b>`
                );
            
                sentenceEl.innerHTML = sentenceEl.innerHTML.replace(
                  // case-insensitive regular expression
                  new RegExp(word, "gi"), `<b><span style=' '>${word}</span></b>`
                );
            
    
              })();
            </script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search