only keep A-Z 0-9 and remove other characters from

2019-03-12 04:43发布

问题:

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

回答1:

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"

Because there is a plus sign at the end of the regular expression it matches one or more characters. Thus, the output will always have one '-' for each series of one or more non-alphanumeric characters:

# An example to demonstrate the effect of the plus sign in the regular expression above
var foo = "  Hello   World    . . .     ".cleanup(); // "-hello-world-"

Without the plus sign the result would be "--hello-world--------------" for the last example.



回答2:

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

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


回答3:

Assuming that the string is kept in a variable called BizName:

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

BizName should now only involve the characters requested.