JavaScript : Extract numeric text from a string

To extract the numeric values from a given text we make use of the JavaScript string match function.

Function name Syntax Function Return value
match ( ) string . match ( regex )
Example: text.match(/\d+(.\d+)?/g);
The match function searches a given
text matching with a regular expression.
If the match succeeds, the function returns an array of matches.
If match doesn’t succeed, the function returns a null.

JavaScript & HTML : Program to extract numeric text from a string.

<!DOCTYPE html>
<html>
<body>

<h1>Extract numeric strings using match() function</h1>

<h2>match() searches for a matching regular expression.</h2>
<label id="id_str" name="name_str">This_string_contains_foo33.44bar5_6.7_and_554.44.55_some444_random_numeric_90values</label>
<p id="numeric_values"></p>

<script>
    let text = document.getElementById("id_str").textContent;
    let result = text.match(/\d+(\.\d+)?/g);
    document.getElementById("numeric_values").innerHTML = result;
</script>

</body>
</html>

Try it out :
https://jsfiddle.net/algotree/k32frhnz/


Javascript : Program to extract numeric text from a string

let text = "A_string_containing_44_7.2_22.2.4_some_numeric_text_foo312.5bar5abc1.1";
let num_array = text.match(/\d+(\.\d+)?/g);
if (num_array != null) {
    console.log("Extracted numeric values : " + num_array);
} else {
    console.log("String contains no numeric value");
}

Output

Extracted numeric values : 44,7.2,22.2,4,312.5,5,1.1


Copyright (c) 2019-2022, Algotree.org.
All rights reserved.