0

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.

Frank E
  • 45
  • 1
  • 7
  • Could you add a snippet to demonstrate the issue you are experiencing. – phuzi Jan 07 '21 at 10:24
  • your regular expression is equivalent to `/[^\s]tring[^\r\n]fromCharCode8222/g`. Check out the [RegExp() constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/RegExp). – Thomas Jan 07 '21 at 10:32
  • No need to use a regular expression for such a simple use case. `replace` will accept a string to find and replace i.e. `cSub.replace(String.fromCharCode(8222), " ")` – phuzi Jan 07 '21 at 11:01

2 Answers2

2

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>
KooiInc
  • 119,216
  • 31
  • 141
  • 177
0

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>
phuzi
  • 12,078
  • 3
  • 26
  • 50