简体   繁体   中英

Javascript .replace() does nothing to string

As a web developer with over 2 years of experience, I am embarrassed to ask this but -

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. I have tried it in my browser and in an open testing environment such as jsbin.com and results are the same.

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/

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.

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.

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 . 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 . You should remove "" If you want to create regular expression with string. You can use RegExp()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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