简体   繁体   中英

How to get a substring in JS

I have a search input and I need to bold a mathcing part of the string in result.
For example:

input : mac
Search results :
mac book pro 16
i Mac 27"
Important mac OS tips

I tried do something like that:

let results = document.querySelectorAll('.search-result-child');
    results.forEach(result => {
                let resultText = result.children[0].innerText;
                let startText = resultText.toLowerCase().indexOf(searchInput.value.toLowerCase());

                let matchingWord = resultText.toLowerCase().substring(startText);
                let newWord = `${resultText.substring(0, startText)}<b>${matchingWord}</b>${partAfterMatchingWordHere}`;

                result.children[0].innerHTML = newWord;
            })

But in that case I don't know how to get the end index
So in word "mac book pro" - the first index need to be 0 and the last need to be 2.

If you have a solution for it or a best way to do that please help me

I was able to do it thanks to https://stackoverflow.com/users/12270289/klaycon

Code:

let results = document.querySelectorAll('.search-result-child');
      results.forEach(result => {
                let resultText = result.children[0].innerText;
                let newWord = resultText.toLowerCase().replace(searchInput.value.toLowerCase(), `<b>${searchInput.value}</b>`);
                result.children[0].innerHTML = newWord;
            })

You can add (String.length-1) to the start index to get the ending index

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM