views:

416

answers:

3

i am trying to verify strings to make valid urls our of them

i need to only keep A-Z 0-9 and remove other characters from string using javascript or jquery

for example :

Belle’s Restaurant

i need to convert it to :

Belle-s-Restaurant

so characters ’s removed and only A-Z a-z 0-9 are kept

thanks

+3  A: 

By adding our .cleanup() method to the String object itself, you can then cleanup any string in Javascript simply by calling a local method, like this:

# Attaching our method to the String Object
String.prototype.cleanup = function() {
   return this.toLowerCase().replace(/[^a-zA-Z0-9]+/g, "-");
}

# Using our new .cleanup() method
var clean = "Hello World".cleanup(); // hello-world
Jonathan Sampson
+1  A: 

Or this if you wanted to put dashes in the place of other chars:

string.replace(/[^a-zA-Z0-9]/g,'-');
Nicolás
+2  A: 

Assuming the string is kept in a string called BizName:

BizName.replace(/[^a-zA-Z0-9]/g, '-');

BizName should now only involve the characters requested.

TodPunk