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

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.


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

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