更换163;使用javascript从html文本区域中提取字符

Replacing £ character from html textarea using javascript

本文关键字:区域 文本 提取 字符 html 使用 javascript 更换      更新时间:2023-09-26

我目前正在开发一个使用html和JavaScript的简单web应用程序,我正在尝试对从html文本区域接收到的字符串进行简单的字符串替换调用;

var contents = document.getElementById("contents").value;
var alteredText = contents.replace(/£/g, "poundsign");

问题是,当字符串中包含£符号时,replace调用找不到它。我通过控制台查看了代码,似乎只要JavaScript中有$符号,它就会在£符号上添加一个",所以

string.replace(/£/g, "poundsign");

正如在js文件中所写的那样,在运行时变成了以下内容:

string.replace(/£/g, "poundsign");

而var内容中的£仍然只是£(将£放入文本区域会导致replace调用正常工作)。有没有办法停止在js文件中添加,或者在调用.replacement之前将其添加到html文件中?

据我所见,只要£出现在js文件中,就会添加£,如果用户自己不将£添加到html中,我就无法将其与html匹配。

   // replace pound string by empty string
   var mystr = '£';
   mystr = mystr.replace(/£/g,'poundsign');
   alert(mystr);

感谢@David Guan的链接,这让我走上了正轨,也感谢所有发表评论的人。

当我在.replace调用中使用Unicode编号而不是字符时,这个问题得到了解决,然后它能够正确匹配£符号,而不需要插入。