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.
I'd suggest:
var inputString = "~!@#$%^&*()_+=`{}[]|\:;'<>,./?Some actual text to keep, maybe...",
outputString = inputString.replace(/([~!@#$%^&*()_+=`{}\[\]\|\\:;'<>,.\/? ])+/g, '-').replace(/^(-)+|(-)+$/g,'');
console.log(outputString);
JS Fiddle demo.
Going by your comment and example:
return mystring.trim().replace(/["~!@#$%^&*\(\)_+=`{}\[\]\|\\:;'<>,.\/?"\- \t\r\n]+/g, '-');
or to replace all non-alphanumeric characters:
return mystring.trim().replace(/[^a-z0-9]+/gi, '-');
You might also add:
.replace(/^-+/, '').replace(/-+$/, '');
to kill off any leading or trailing dashes (at which point you no longer need to call trim()
).
Example:
function cleanUp(st) {
return st.
replace(/[^a-z0-9]+/gi, '-').
replace(/^-+/, '').
replace(/-+$/, '');
}
var mystring="Need !@#$%^\" to /replace this*(){}{}|\><? with_new string ";
console.log( cleanUp(mystring) );
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