How to Remove Text from String

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

replace()

Widely used method for such task is the replace() method:

Javascript replace method remove text from string
let someVar = "text-1324".replace('text-', ''); console.log(someVar); //prints: 1324

To discard all the occurrences of the string, you use regexp along with the global property which selects every occurrence in the string:

Javascript regexp and replace method remove text from string
let someVar = "text-1324".replace(/text-/g, ''); console.log(someVar); //prints: 1324

Use the returned value of the function after the replace() call as the replace function leaves the original string unchanged.

Number() and match()

This method appends regexp and match() to the given string and gets the output as number:

Javascript regexp and match method remove text from string
let someVar = Number(("text-1324").match(/\d+$/)); console.log(someVar); //prints: 1324

The replace() Method

The replace method is used for replacing the given string with another string. It takes two parameters the first one is the string that should be replaced and the second one is the string which is replacing from the first string. The second string can be given an empty string so that the text to be replaced is removed.

Number() and match()

The match() method returns an array that contains matches to any length of numbers at the end of the string.

The Number() is a built-in JavaScript function that converts data type into a number. As the array returned from match() contains a single element, Number() will return the number.