user2643287 user2643287 - 1 year ago 85
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

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

But it's outputting this:


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

Answer Source

I'd suggest:

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

JS Fiddle demo.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download