W3docs

How to Remove Text from String

Read this JavaScript tutorial and learn useful information about several easy and fast built-in methods that are used for removing the text from a string.

There are several methods used in JavaScript that can remove a substring from a string. Let’s discuss them below.

replace()

The widely used method for this task is the <kbd class="highlighted">replace()</kbd> method:

Javascript replace method remove text from string

javascript— editable

To remove all occurrences of a substring, you can use a regular expression with the global flag (g), which selects every match in the string:

Javascript regexp and replace method remove text from string

javascript— editable

In modern JavaScript, you can also use the <kbd class="highlighted">replaceAll()</kbd> method for cleaner global replacement without regex flags:

javascript— editable

Always use the returned value of the function, as <kbd class="highlighted">replace()</kbd> leaves the original string unchanged.

Number() and match()

This approach combines a regular expression with <kbd class="highlighted">match()</kbd> to extract specific content, and then converts the result to a number using <kbd class="highlighted">Number()</kbd>:

Javascript regexp and match method remove text from string

javascript— editable

The <kbd class="highlighted">match()</kbd> method returns an array containing the matched substring, or null if no match is found. The <kbd class="highlighted">Number()</kbd> function then converts that string into a numeric value. Note that if the pattern is not found, match() returns null, and Number(null) evaluates to 0. Using optional chaining (?.[0]) and a fallback ensures safe conversion.