Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 244
EzzDev Avatar asked Dec 31 '09 03:12

EzzDev


People also ask

How do you remove all characters from a string after a specific character in JavaScript?

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.

How do I remove a character from a number string?

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.

How do I remove a character from the end of a string in JavaScript?

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) .


2 Answers

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.

like image 192
Sampson Avatar answered Sep 23 '22 06:09

Sampson


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

string.replace(/[^a-zA-Z0-9]/g,'-'); 
like image 30
Nicolás Avatar answered Sep 20 '22 06:09

Nicolás