javascript 如何从字符串中删除控制字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26741455/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove control characters from string?
提问by user606521
I have form on my page where user can type some text and submit it. Text is then sent to server (REST API on top of node.js) and saved to DB (postgres).
我的页面上有表单,用户可以在其中输入一些文本并提交。然后将文本发送到服务器(node.js 之上的 REST API)并保存到数据库(postgres)。
The problem is that some strange characters (control characters) are saved to DB occasionaly - for example escape control character (^[) or backspace control character (^H). Generally it does not break anything since those characters are invisible, so html is rendered correctly. However when I provide xml content for RSS readers, they (readers) return "Malformed XML" because of those control characters (it works after deleting them).
问题是一些奇怪的字符(控制字符)偶尔会保存到 DB - 例如转义控制字符 (^[) 或退格控制字符 (^H)。通常它不会破坏任何东西,因为这些字符是不可见的,因此 html 可以正确呈现。但是,当我为 RSS 阅读器提供 xml 内容时,他们(阅读器)由于这些控制字符而返回“格式错误的 XML”(删除它们后可以正常工作)。
My question is how I can remove those characters from a string on client level (javascript) or server level (javascript/node.js)?
我的问题是如何从客户端级别(javascript)或服务器级别(javascript/node.js)的字符串中删除这些字符?
回答by Rory O'Kane
I have found the right answer in the text of this question: Removing control characters from a UTF-8 string in PHP. Use a regexp to find the control characters and replace them with an empty string:
我在这个问题的文本中找到了正确的答案:Removing control characters from a UTF-8 string in PHP。使用正则表达式查找控制字符并将其替换为空字符串:
str.replace(/[\x00-\x1F\x7F-\x9F]/g, "");
回答by Mateen
I had the similar problem, here's the solution which i choose.
我有类似的问题,这是我选择的解决方案。
I encoded the string data from the user using encodeURIComponent(variable_Name) and then saved then while displaying i decoded using decodeURIComponent(variable_Name)
我使用 encodeURIComponent(variable_Name) 对来自用户的字符串数据进行编码,然后在显示时保存然后使用 decodeURIComponent(variable_Name) 解码