Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
366 views
in Technique[技术] by (71.8m points)

Javascript: Replace special character code 8222 fails

In Germany, text processors in its wisdom like to put lower quotes at the beginning of a word and upper at the end. So you end up with a text with unicode 8222 codes in there and running .search(String.fromCharCode(8222)) finds the occurrence just fine and also String.fromCharCode(8222) shows the character just fine.

However, now it gets problematic - with fromCharCode finding the character, I would imagine below code would replace it with space:

cSub.replace(/String.fromCharCode(8222)/g, " ")

But it doesn't, also this does not work:

cSub.replace(/String.fromCharCode(8222)/g, " ")

In both cases, the string comes back unchanged. I am close to write a own replace-routine, but that should not be the solution, I guess ?

Any suggestions as to how I can replace the 8222 characters with space ?

Thanks so much

Frank

https://jsfiddle.net/y9cb2e1v/12/ to try it out.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You cant't use a Regular Expression literal like that. Try to create a RegExp like this:

const re = RegExp(`[${String.fromCharCode(8222)}${String.fromCharCode(8221)}]`, "g");
console.log(`Your RegExp ${re}`);
console.log(document.querySelector("div").textContent.replace(re, "!"));
<div>"Something &#8222;quoted&#8221;"</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...