Remove spaces, periods and special characters from a string and replace hyphen in jQuery

I have a line where there may be special characters that I need to replace with defam

var str="123.This is,, :ravi" 

The above line should be converted as follows

 var newstr="123-This-is-ravi"; 

I tried this

 function remove(str){ str.replace(/\./g, "-"); } //replaces only dots function remove(str){ str.replace(/ /g, "-"); } //replaces only spaces 

Can someone help me do this? I need to replace special characters with a hyphen.

+7
source share
2 answers

You should do the regex immediately :

 "123.This is,, :ravi".replace(/[\. ,:-]+/g, "-") 

Thus, it will not double on hyphens.

It should be noted that if the value ends with a period (dot) or even any space, then it ends with a hyphen.

+16
source

You can also try globally replacing any alphanumeric character and space using the function

 "123.This is,, :ravi".replace(/[\W_]/g, "-") 

/ [\ W _] / g globally excludes any non-alphanumeric characters and spaces and can be replaced with anything you choose after the decimal point,

+7
source

All Articles