简体   繁体   中英

JavaScript replace special HTML (&character; format) character in a String

I'm trying to replace the square root symbol which is written in html as "√" ( √ ). I used the following line to replace it with a space but it does not change the String at all.

 dig = document.getElementById("dig").innerHTML; dig = dig.replace(/'√'/g, ' '); console.log(dig);
 <div id="dig">&radic;25</div>

What am I doing wrong here?

This answer is valid if you are accessing the innerText or innerHTML atribute of an Element .

 let s = document.getElementById("sqrt") console.log("Text", s.innerText) console.log(s.innerText.replace(/√/g, "")) console.log(s.innerHTML.replace(/√/g, ""))
 <div id="sqrt"> &radic;2 == 1.4142</div>

As you can see &radic; gets evaluated and it's value is then instead of that. The javascript replace method cannot understand that is &radic so you can just replace .

Also there is no need to use regex, you can just do the same with "√"

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