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.
The $. trim() function removes all newlines, spaces (including non-breaking spaces), and tabs from the beginning and end of the supplied string.
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.
replace() We can use replace() to remove all the whitespaces from the string. This function will remove whitespaces between words too.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With