Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

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.

like image 966
user2643287 Avatar asked Sep 21 '13 19:09

user2643287


2 Answers

I'd suggest:

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

JS Fiddle demo.

like image 159
David Thomas Avatar answered Oct 26 '22 13:10

David Thomas


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) );
like image 39
Paul Roub Avatar answered Oct 26 '22 13:10

Paul Roub