Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
194
rated 0 times [  200] [ 6]  / answers: 1 / hits: 46910  / 15 Years ago, thu, december 31, 2009, 12:00:00

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


More From » string

 Answers
43

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.


[#97956] Saturday, December 26, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
everardo

Total Points: 406
Total Questions: 104
Total Answers: 92

Location: Albania
Member since Sun, Nov 22, 2020
4 Years ago
;