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
slice() method to remove everything after a specific character, e.g. const removed = str. slice(0, str. indexOf('[')); . The slice method will return the part of the string before the specified character.
Using 'str. replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.
To remove the last character from a string in JavaScript, you should use the slice() method. It takes two arguments: the start index and the end index. slice() supports negative indexing, which means that slice(0, -1) is equivalent to slice(0, str. length - 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.
Or this if you wanted to put dashes in the place of other chars:
string.replace(/[^a-zA-Z0-9]/g,'-');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With