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:
To discard all the occurrences of the string, you use regexp along with the global property which selects every occurrence in the string:
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:
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.