Punctuation marks
Here’s a string of English punctuation marks:
var punctuation = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~';
Remove using iteration
To remove punctuation with JavaScript, you can iterate through each letter and filter out the letters that don’t match:
var rawString = 'Hello, world!';
var rawLetters = rawString.split('');
var cleanLetters = rawLetters.filter(function(letter) {
return punctuation.indexOf(letter) === -1;
});
var cleanString = cleanLetters.join('');
Here’s a function that removes punctuation marks using iteration:
var punctuation = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~';
function removePunctuation(string) {
return string
.split('')
.filter(function(letter) {
return punctuation.indexOf(letter) === -1;
})
.join('');
}
Remove using regex
Instead of storing the punctuation marks as a string, you can store it as a Regular Expression:
var regex = new RegExp('[' + punctuation + ']', 'g');
The following regex is the same as the above:
var regex = /[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]/g;
With regex, you can replace all matches with an empty string:
var rawString = 'Hello, world!';
var cleanString = rawString.replace(regex, '');
Here’s a function that removes punctuation marks using regex:
var regex = /[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]/g;
function removePunctuation(string) {
return string.replace(regex, '');
}
Demo
See Repl.it demo:
You can also find the code in this Gist.