简体   繁体   English

Javascript .replace()不执行任何字符串操作

[英]Javascript .replace() does nothing to string

As a web developer with over 2 years of experience, I am embarrassed to ask this but - 作为拥有2年以上经验的Web开发人员,我很尴尬地问这个问题,但是-

the following code does not work as intended : 以下代码无法正常工作:

var string = "Daln, nik, But, Blaz, wan";
string = string.replace("/[^a-zA-Z,]+/g", "");

if the string is not being stripped of the spaces, I mean even if I set this as a regex 如果字符串没有被删除,我的意思是即使我将其设置为正则表达式

var string = "Daln, nik, But, Blaz, wan";
string = string.replace("/[a-zA-Z,]+/g", "");

where it should replace any character from a to z both upper and lowercase, and any commas, it does not. 它应该替换从a到z的任何字符(大写和小写)以及任何逗号,但不能替换。 I have tried it in my browser and in an open testing environment such as jsbin.com and results are the same. 我已经在浏览器和开放式测试环境(例如jsbin.com)中进行了尝试,结果是相同的。

Contratry to my belief that something might be wrong with the regex, it seems to be working fine as a stand-alone, this has been proven by this live testing tool https://regexr.com/ 与我的看法相反,正则表达式可能有问题,它似乎可以独立运行,这已经通过实时测试工具https://regexr.com/进行了证明。

So here I am wondering what in hell's name is wrong, and I am thankful to anyone who helps out ! 所以在这里,我想知道到底是什么名字错了,并且我感谢任何提供帮助的人!

You're passing replace a string and not a regular expression. 您正在传递replace字符串而不是正则表达式。

Remove the " characters from around the regular expression. 从正则表达式周围删除"字符。

It does nothing, because you are trying to replace the string "/[a-zA-Z,]+/g" which does not exists. 它没有任何作用,因为您试图替换不存在的字符串"/[a-zA-Z,]+/g"

You need to remove the quotes to effectively use the regex : 您需要删除引号以有效使用正则表达式:

var string = "Daln, nik, But, Blaz, wan";
string = string.replace(/[a-zA-Z,]+/g, "");

You are not passing regular expression as argument. 您没有将正则表达式作为参数传递。 You are passing string . 您正在传递string According to docs. 根据文档。

Regular expression literal: which consists of a pattern enclosed between slashes( // ). 正则表达式文字:由斜线( // )之间的模式组成。

You are wrapping your expression in "" quotes. 您将表达式用""引号引起来。 Which makes it a string . 这使它成为string You should remove "" If you want to create regular expression with string. 如果要使用字符串创建正则表达式,则应删除"" You can use RegExp() 您可以使用RegExp()

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

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