Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove characters from a string

What are the different ways I can remove characters from a string in JavaScript?

like image 484
Skizit Avatar asked Jan 31 '11 01:01

Skizit


People also ask

How do I remove multiple characters from a string?

To remove multiple characters from a string we can easily use the function str. replace and pass a parameter multiple characters. The String class (Str) provides a method to replace(old_str, new_str) to replace the sub-strings in a string. It replaces all the elements of the old sub-string with the new sub-string.

Can you remove characters from a string Python?

You can remove a character from a Python string using replace() or translate(). Both these methods replace a character or string with a given value. If an empty string is specified, the character or string you select is removed from the string without a replacement.

How do you remove a character from a string in Java?

Use the deleteCharAt Method to Remove a Character From String in Java. The deleteCharAt() method is a member method of the StringBuilder class that can also be used to remove a character from a string in Java.


2 Answers

Using replace() with regular expressions is the most flexible/powerful. It's also the only way to globally replace every instance of a search pattern in JavaScript. The non-regex variant of replace() will only replace the first instance.

For example:

var str = "foo gar gaz";  // returns: "foo bar gaz" str.replace('g', 'b');  // returns: "foo bar baz" str = str.replace(/g/gi, 'b'); 

In the latter example, the trailing /gi indicates case-insensitivity and global replacement (meaning that not just the first instance should be replaced), which is what you typically want when you're replacing in strings.

To remove characters, use an empty string as the replacement:

var str = "foo bar baz";  // returns: "foo r z" str.replace(/ba/gi, ''); 
like image 187
Dave Ward Avatar answered Oct 07 '22 09:10

Dave Ward


ONELINER which remove characters LIST (more than one at once) - for example remove +,-, ,(,) from telephone number:

var str = "+(48) 123-456-789".replace(/[-+()\s]/g, '');  // result: "48123456789" 

We use regular expression [-+()\s] where we put unwanted characters between [ and ]

(the "\s" is 'space' character escape - for more info google 'character escapes in in regexp')

like image 34
Kamil Kiełczewski Avatar answered Oct 07 '22 11:10

Kamil Kiełczewski