Friday, December 27, 2024
Google search engine
HomeLanguagesJavascriptHow to Remove Punctuation from Text using JavaScript ?

How to Remove Punctuation from Text using JavaScript ?

In this article, 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 @neveropenforgeek<s
Output : welcome to neveropen

Below are the following approaches through which we can remove punctuation from text using JavaScript:

  • Using replace() Method with Regular Expression
  • Using for Loop

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 neveropen!!!";
console.log(remove(str));


Output

Welcome to the neveropen

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 neveropen!!!";
console.log(remove(str));


Output

Welcome to the neveropen
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments