I am creating function in which I will pass String and Specific text.The specific text should be bold in whole string. I want to achieve this but unable do that.
Input string:-"Hi Hello boy Hello Shyam Hello"
Text:- Hello.
Output:- Hello word should looks bold in String.
I'd do it like this:
function escapeRegExp(text) { return text.replace(/[-[\]{}()*+?.,\\^$|#\\s]/g, '\\$&'); } function boldMe(input, text){ const regExString = escapeRegExp(text) const regex = new RegExp(regExString, 'g'); let output = input.replace(regex, `<b>${text}</b>`); console.log(output); return output; } var myDev = document.getElementById('myDiv'); myDev.innerHTML = boldMe(myDev.innerHTML,'Hello');
<div id="myDiv">Hi Hello boy Hello Shyam Hello</div>
Edit:
As @Peter Seliger pointed out in the comments, since working with regex, the search string has to be escaped before being used. I used this approach , but feel free to use any other escaping implementation
<span id="boldit">Bold me</span>
<script>
function boldme() {
document.getElementById('boldit').style.fontWeight = 'bold';
}
boldme();
</script>
function boldString (fString, bString) { let regex = new RegExp(bString, 'g'); return fString.replace(regex, `<b>${bString}</b>`); } let output = boldString("Hi Hello boy Hello Shyam Hello", "Hello"); console.log(output); document.body.innerHTML = output;
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.