Javascript:替换特殊字符代码 8222 失败

问题描述

在德国,文本处理程序喜欢在单词的开头加上小引号,在单词的结尾加上大引号。因此,您最终会得到一个带有 unicode 8222 代码的文本,然后运行 ​​.search(String.fromCharCode(8222)) 会发现出现的情况很好,而且 String.fromCharCode(8222) 显示的字符也很好。

但是,现在出现了问题 - fromCharCode 找到了字符,我想下面的代码会用空格替换它:

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

但它没有,这也不起作用:

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

在这两种情况下,字符串都保持不变。我即将编写自己的替换例程,但这不应该是解决方案,我猜?

关于如何用空格替换 8222 个字符的任何建议?

非常感谢

弗兰克

https://jsfiddle.net/y9cb2e1v/12/ 尝试一下。

解决方法

你不能像那样使用正则表达式文字。尝试像这样创建一个 RegExp

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>

,

您可以通过传递特定值来使用不带正则表达式的 replace

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>