How to Remove Punctuation from Text using JavaScript ?
Last Updated : 31 May, 2024
We will learn how to remove punctuation from text using JavaScript. Given a string, remove the punctuation from the string if the given character is a punctuation character, as classified by the current C locale. The default C locale classifies these characters as punctuation:
! " # $ % & ' ( ) * + , - . / : ; ? @ [ \ ] ^ _ ` { | } ~
Examples:
Input : %welcome' to @geeksforgeek<s
Output : welcome to geeksforgeeks
Below are the following approaches through which we can remove punctuation from text using JavaScript:
Approach 1: Using replace() Method with Regular Expression
In this approach, we will use the replace() method with a regular expression and replace punctuations with an empty string.
Example:
JavaScript function remove(str) { return str.replace(/[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]/g, ''); } let str = "Welcome, to the geeksforgeeks!!!"; console.log(remove(str));
OutputWelcome to the geeksforgeeks
Approach 2: Using for loop
In this approach we will use for loop to iterate over the string and make the function for checking the punctuation. If the character is punctuation marks then it will not add in result variable and if it is not then we concat it to the result variable.
JavaScript function remove(str) { let res = ''; for (let i = 0; i < str.length; i++) { let character = str.charAt(i); if (!checkPunctuation(character)) { res += character; } } return res; } function checkPunctuation(char) { const punctuation = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'; return punctuation.includes(char); } let str = "Welcome, to the geeksforgeeks!!!"; console.log(remove(str));
OutputWelcome to the geeksforgeeks
Approach 3: Using split, filter, and join
In this approach we are using split, filter, and join in JavaScript removes punctuation from a string.We start by splitting the string into an array of characters, then filtering out characters that are not letters, numbers, or spaces using a, and finally we will join the filtered array back into a string.
Example: In this example we defines a function to remove punctuation from a string using split, filter, and join methods. It cleans the text by keeping only alphanumeric characters and spaces.
JavaScript function removePunctuation(str) { return str.split('').filter(char => { return /[a-zA-Z0-9 ]/.test(char); }).join(''); } let text = "GeeksforGeeks a computer science portal."; let cleanedText = removePunctuation(text); console.log(cleanedText);
OutputGeeksforGeeks a computer science portal
Approach 4: Using ASCII Values
In this approach we will iterate over each character in text and checks if it is punctuation based on its ASCII value. If it is punctuation ew exclude it otherwise we append that character to result.
Example: In this example we defines a function to remove punctuation from a string using ASCII Values. It cleans the text by keeping only alphanumeric characters and spaces.
JavaScript function removePunctuation(text) { let result = ""; for (let i = 0; i < text.length; i++) { let charCode = text.charCodeAt(i); // Check if the character is not a punctuation character (33-47, 58-64, 91-96, 123-126 in ASCII) if ((charCode < 33 || charCode > 47) && (charCode < 58 || charCode > 64) && (charCode < 91 || charCode > 96) && (charCode < 123 || charCode > 126)) { result += text[i]; } } return result; } let text = "Hello, Geek. Welcome to GFG!"; let cleanedText = removePunctuation(text); console.log(cleanedText);
OutputHello Geek Welcome to GFG
Approach 5: Using filter() Method with an Array
The `filter()` method splits the text into an array of characters. It filters out punctuation characters using a regular expression, leaving only alphanumeric characters. Finally, it joins the filtered characters back into a string.
Example:
JavaScript function removePunctuation(text) { return [...text].filter(char => /[^\W_]/.test(char)).join(''); } console.log(removePunctuation("Hello, world! This is a test.")); // "Hello world This is a test"
OutputHelloworldThisisatest
Approach 6: Using Array.from() and Array.filter()
This method utilizes the Array.from() method to create an array from the string and then applies the Array.filter() method to remove punctuation characters based on their Unicode category.
Example:
JavaScript function removePunctuation(str) { return Array.from(str).filter(char => { const charCode = char.charCodeAt(0); return !(charCode >= 33 && charCode <= 47) && !(charCode >= 58 && charCode <= 64) && !(charCode >= 91 && charCode <= 96) && !(charCode >= 123 && charCode <= 126); }).join(''); } let str = "Welcome, to the geeksforgeeks!!!"; console.log(removePunctuation(str)); // Output: Welcome to the geeksforgeeks
OutputWelcome to the geeksforgeeks
Similar Reads
JavaScript Program to Remove Vowels from a String The task is to write a JavaScript program that takes a string as input and returns the same string with all vowels removed. This means any occurrence of 'a', 'e', 'i', 'o', 'u' (both uppercase and lowercase) should be eliminated from the string. Given a string, remove the vowels from the string and
2 min read
JavaScript- Remove Last Characters from JS String These are the following ways to remove first and last characters from a String:1. Using String slice() MethodThe slice() method returns a part of a string by specifying the start and end indices. To remove the last character, we slice the string from the start (index 0) to the second-to-last charact
2 min read
JavaScript Program to Remove Last Character from the String In this article, we will learn how to remove the last character from the string in JavaScript. The string is used to represent the sequence of characters. Now, we will remove the last character from this string. Example: Input : Geeks for geeks Output : Geeks for geek Input : Geeksforgeeks Output :
3 min read
How to Convert Char to String in JavaScript ? In the article, we are going to learn about conversion Char to a string by using JavaScript, Converting a character to a string in JavaScript involves treating the character as a string, a character is a single symbol or letter, while a string is a sequence of characters. Strings can contain multipl
3 min read
JavaScript - Remove all Occurrences of a Character in JS String These are the following ways to remove all occurrence of a character from a given string: 1. Using Regular ExpressionUsing a regular expression, we create a pattern to match all occurrences of a specific character in a string and replace them with an empty string, effectively removing that character
2 min read
JavaScript - How to Replace Multiple Characters in a String? Here are the various methods to replace multiple characters in a string in JavaScript.1. Using replace() Method with Regular ExpressionThe replace() method with a regular expression is a simple and efficient way to replace multiple characters.JavaScriptconst s1 = "hello world!"; const s2 = s1.replac
3 min read