user2643287 user2643287 - 1 month ago 14
jQuery Question

Regex for replacing all special characters and spaces in a string with hyphens

I have a string in which I need to replace all the special characters "~!@#$%^&*()_+=`{}[]|:;'<>,./?" and spaces with hyphens. Multiple special characters in a row should result in a single hyphen.

var mystring="Need !@#$%^\" to /replace this*(){}{}|\><? with_new string ";
// desired output: "Need-to-replace-this-with-new-string"


At present, I'm using this series of
replace()
calls:

return mystring.replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '-').replace(/\//g, "-");


But it's outputting this:

Need----------to/replace-this--------with-new-string;


where it's adding a hyphen for every special character in the string except for the forward slash.

Answer

I'd suggest:

var inputString = "~!@#$%^&*()_+=`{}[]|\:;'<>,./?Some actual text to keep, maybe...",
    outputString = inputString.replace(/([~!@#$%^&*()_+=`{}\[\]\|\\:;'<>,.\/? ])+/g, '-').replace(/^(-)+|(-)+$/g,'');
console.log(outputString);

JS Fiddle demo.