Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript remove fullstop, comma and spaces from a string

I'm trying to remove the fullstops, commas and spaces from a string. I'm pretty sure I have to do this using this: str.replace(<some Regex here>, "");

I'm just not very familiar with Regex, how can I accomplish this?

like image 861
Barry Michael Doyle Avatar asked Apr 23 '16 22:04

Barry Michael Doyle


People also ask

How do I remove special characters and spaces from a string?

Use the replace() method to remove all special characters from a string, e.g. str. replace(/[^a-zA-Z0-9 ]/g, ''); .

How do I remove spaces in JavaScript?

JavaScript String trim() The trim() method removes whitespace from both sides of a string. The trim() method does not change the original string.

How do you remove all commas in a string?

To remove all commas from a string, call the replace() method, passing it a regular expression to match all commas as the first parameter and an empty string as the second parameter. The replace method will return a new string with all of the commas removed.

How do you find and replace a character in a string in JavaScript?

Answer: Use the JavaScript replace() method You can use the JavaScript replace() method to replace the occurrence of any character in a string. However, the replace() will only replace the first occurrence of the specified character. To replace all the occurrence you can use the global ( g ) modifier.


1 Answers

Use this regex /[.,\s]/g

var str = 'abc abc a, .aa ';

var regex = /[.,\s]/g;

var result = str.replace(regex, '');

document.write(result);

You don't need to escape character except ^-]\ in character class []

Any character except ^-]\ add that character to the possible matches for the character class.

like image 190
isvforall Avatar answered Oct 02 '22 02:10

isvforall