Javascript: Replace special character code 8222 fails

422 Views Asked by At

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.

2

There are 2 best solutions below

0
KooiInc On BEST ANSWER

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>

0
phuzi On

You can use replace without a regular expression by passing a specific value.

function start() {

  var cId = "w3review";

  var cTxt = document.getElementById(cId).value;

  cSub = cTxt.replace(String.fromCharCode(8222), " ");

  var iPos = cTxt.search(String.fromCharCode(8222));

  document.getElementById("txtout").value = "Result: Character found at position " + iPos + ", result from replace: " + cSub;

}
<textarea id="w3review" rows="5" cols="40">
Source Value:
kennen. &bdquo;Neurons that fire
</textarea>

<button onclick="start()">Click me</button>

<textarea id="txtout" rows="5" cols="40">
</textarea>