user1831498
user1831498

Reputation: 97

Remove spaces , dots and special chars from a string and replace with hyphen in jQuery

I have a string where there may be special characters, which I have to replace with hyphen

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

The above string should be converted like this

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

I have been trying this

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

Can any one help me doing this? I need to replace special chars with hyphen.

Upvotes: 9

Views: 36698

Answers (2)

pickypg
pickypg

Reputation: 22332

You should do the regular expression all at once:

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

Working example:

$('p').html("123.This is,, :ravi".replace(/[\. ,:-]+/g, "-"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p></p>

That way it will not double up on hyphens.

One thing to note is that if the value ends with a period (dot), or even any whitespace, then it will end with a hyphen.

Upvotes: 25

Iya F.
Iya F.

Reputation: 129

You could also try to globally replace any non-alphanumeric character and white space by using the function

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

/[\W_]/g this globally eliminates any non alphanumeric characters and white spaces and can be replaced by anything you chose after the comma,

Upvotes: 11

Related Questions