简体   繁体   English

使用JavaScript中的RegEx从字符串中删除斜杠

[英]Remove slashes from string using RegEx in JavaScript

I am trying to remove all special characters except punctuation from a customer complaint textarea using this code: 我正在尝试使用以下代码从客户投诉文本区域中删除标点符号以外的所有特殊字符:

var tmp = complaint;
complaint = new RegExp(tmp.replace(/[^a-zA-Z,.!?\d\s:]/gi, ''));

but it keeps placing "/" in front, and in back of the string after sanitizing. 但在消毒后,它始终在字符串的前面和后面放置“ /”。

Example: 例:

 Hi, I h@ve a% probl&em wit#h (one) of your products.

Comes out like this 这样出来

 /Hi, I have a problem with one of your products./

I want 我想要

 Hi, I have a problem with one of your products.

Thanks in advance for any help given. 在此先感谢您提供的任何帮助。

The variable complaint is converted to a regular expression because you use the RegExp() constructor. 因为您使用了RegExp()构造函数,所以将变量complaint转换为正则表达式。

This probably isn't what you want. 这可能不是您想要的。 (I assume you want complaint to be a string). (我假设您希望complaint为字符串)。

Strings and regular expressions are two completely different data types. 字符串和正则表达式是两种完全不同的数据类型。

Your output demonstrates how JavaScript displays regular expressions (surrounded by / characters). 您的输出演示了JavaScript如何显示正则表达式(用/字符包围)。

If you want a string, don't create a regular expression (ie remove the RegExp constructor ). 如果您想要一个字符串,请不要创建正则表达式(即,删除RegExp构造函数 )。

In other words: 换一种说法:

complaint = complaint.replace(/[^a-zA-Z,.!?\d\s:]/gi, '');

您不需要RegExp构造函数:

complaint = tmp.replace(/[^a-zA-Z,.!?\d\s:]/gi, '');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM