Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
18
rated 0 times [  19] [ 1]  / answers: 1 / hits: 36248  / 11 Years ago, tue, april 23, 2013, 12:00:00

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.


More From » jquery

 Answers
12

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.


[#78702] Monday, April 22, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
stephonkeandrer

Total Points: 392
Total Questions: 94
Total Answers: 100

Location: Tajikistan
Member since Sun, Aug 29, 2021
3 Years ago
;