Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 369
user1831498 Avatar asked Apr 23 '13 05:04

user1831498


People also ask

How can remove space from string in jquery?

The $. trim() function removes all newlines, spaces (including non-breaking spaces), and tabs from the beginning and end of the supplied string.

How do you replace spaces with dashes?

Use the replace() method to replace spaces with dashes in a string, e.g. str. replace(/\s+/g, '-') . The replace method will return a new string, where each space is replaced by a dash.

How do you get rid of the middle space in a string?

replace() We can use replace() to remove all the whitespaces from the string. This function will remove whitespaces between words too.


1 Answers

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.

like image 87
pickypg Avatar answered Oct 25 '22 14:10

pickypg