How to Remove Punctuation from String using TypeScript ?
Last Updated :
14 May, 2024
Typescript allows us to remove the punctuation from the string using various methods. Punctuation refers to symbols like commas, periods, and exclamation marks. In TypeScript, to remove punctuation from a string by using these approaches :
Using regular expression
In this approach, we will be using the regular expression to find the punctuation using a pattern and using the replace() method to replace the punctuation with blank spaces to remove them from a string.
Example: This example uses regular expressions to remove the punctuation from a string.
JavaScript
function removePunctuation(text: string): string {
return text
.replace(/[^\w\s]|_/g, "");
}
const text = "Hello, Geek! How are you?";
const cleanText = removePunctuation(text);
console.log(cleanText);
Output:
Hello Geek How are you
Using for loop
In this approach we iterate over each character in the input string using a for loop. For each character, we check if it is a punctuation character by comparing it against a predefined array of punctuation characters. If the character is not a punctuation, we append it to a new string which will eventually contain the cleaned text without any punctuation.
Example: This example uses for loop to remove the punctuation from string.
JavaScript
function removePunctuation(text: string): string {
const punctuation = [".", ",", "!", "?", ";", ":"];
let cleanText = "";
for (let i = 0; i < text.length; i++) {
const char = text[i];
if (!punctuation.includes(char)) {
cleanText += char;
}
}
return cleanText;
}
const text = "Hello user, Welcome to GeeksForGeeks!";
const cleanText = removePunctuation(text);
console.log(cleanText);
Output:
Hello user Welcome to GeeksForGeeks
Using split, filter, and join
In this approach, we use split, filter, and join in JavaScript to remove punctuation from a string. We start by splitting the string into an array of characters, then filter out characters that are not letters, numbers, or spaces and finally join the filtered array back into a string.
Example: This example uses split, filter, and join methods to remove the punctuation from string.
JavaScript
function removePunctuation(str: string): string {
return str.split('').filter(char => /[a-zA-Z0-9 ]/.test(char)).join('');
}
let text: string = "Hello user, Welcome to GFG!";
let cleanedText: string = removePunctuation(text);
console.log(cleanedText);
Output:
Hello user Welcome to GFG
Using ASCII Values
This approach iterates over each character in the input string. For each character, it checks if the character code falls within the range of uppercase letters, lowercase letters, or is equal to the character code for space. If the character is within one of these ranges, it is considered not to be punctuation and is added to the result string.
Example: This example uses ASCII Values to remove the punctuation from string.
JavaScript
function removePunctuation(str: string): string {
let result = '';
for (let i = 0; i < str.length; i++) {
const charCode = str.charCodeAt(i);
if ((charCode >= 65 && charCode <= 90) || // Uppercase letters
(charCode >= 97 && charCode <= 122) || // Lowercase letters
(charCode >= 48 && charCode <= 57) || // Digits
charCode === 32) { // Space character
result += str[i];
}
}
return result;
}
const inputString = "Hello Geek, Welcome to GFG!";
const resultString = removePunctuation(inputString);
console.log(resultString);
Output:
Hello Geek Welcome to GFG
Using String.prototype.replace() with Predefined Punctuation Characters
In this approach, we define a set of punctuation characters and use the String.prototype.replace() method to remove them from the string. We iterate over each punctuation character and replace it with an empty string, effectively removing all punctuation from the string.
Example: This example demonstrates how to remove punctuation from a string using String.prototype.replace() with a predefined set of punctuation characters.
JavaScript
function removePunctuation(text: string): string {
const punctuation = [".", ",", "!", "?", ";", ":"];
punctuation.forEach(p => {
text = text.replace(new RegExp("\\" + p, "g"), "");
});
return text;
}
const text = "Hello, world! How are you?";
const cleanText = removePunctuation(text);
console.log(cleanText);
Output:
"Hello Geek How are you"
Similar Reads
How to remove Punctuation from String in PHP ?
Punctuation removal is often required in text processing and data cleaning tasks to prepare the text for further analysis or display. Below are the methods to remove punctuation from a string in PHP: Table of Content Using preg_replace with a Regular ExpressionUsing str_replace functionUsing preg_re
2 min read
How to Remove Spaces from a String in TypeScript ?
TypeScript offers various inbuilt functions to remove spaces from a string. These functions can be used to remove spaces between characters or entire words. Below, we explore different approaches to remove spaces from a string in TypeScript. Table of Content Using split() and join() methodsUsing rep
4 min read
How to Format Strings in TypeScript ?
Formatting strings in TypeScript involves combining and structuring text to produce clear and readable output. This practice is essential for creating dynamic and user-friendly applications, as it allows developers to seamlessly integrate variables and expressions into strings, enhancing the overall
3 min read
How to Perform String Interpolation in TypeScript?
String interpolation in TypeScript is defined as an expression that is used to evaluate string literals containing expressions. It replaces placeholders with evaluated results, allowing dynamic string generation from static text and variables, making it ideal for templating logic and enhancing code
2 min read
How to parse JSON string in Typescript?
In this tutorial, we will learn how we can parse a JSON string in TypeScript. The main reason for learning about it is to learn how we can explicitly type the resulting string to a matching type. The JSON.parse() method will be used to parse the JSON string by passing the parsing string as a paramet
4 min read
How to remove HTML tags from a string using JavaScript ?
Removing HTML tags from a string in JavaScript means stripping out the markup elements, leaving only the plain text content. This is typically done to sanitize user input or to extract readable text from HTML code, ensuring no unwanted tags remain in the string. HTML tags come in two forms: opening
3 min read
TypeScript | toString() Function
The toString() method in TypeScript is used to return a string representing the specified object radix (base). Syntax:number.toString( [radix] )Parameters:This function accepts a single parameter as mentioned above and described below. radix: This parameter represents an integer between 2 and 36 spe
1 min read
How to Iterate Over Characters of a String in TypeScript ?
In Typescript, iterating over the characters of the string can be done using various approaches. We can use loops, split() method approach to iterate over the characters. Below are the possible approaches: Table of Content Using for LoopUsing forEach() methodUsing split() methodUsing for...of LoopUs
2 min read
How to remove spaces from a string using JavaScript?
These are the following ways to remove space from the given string: 1. Using string.split() and array.join() MethodsJavaScript string.split() method is used to split a string into multiple sub-strings and return them in the form of an array. The join() method is used to join an array of strings usin
2 min read
How to Filter Keys of Type string[] in TypeScript ?
In TypeScript, the filtering of keys of type string[] can be done by iterating over the data object, and applying the condition to the string if the key is a string. If the condition is satisfied, then an array of output results is created which consists of filtered keys of type string[]. The below
3 min read