I'm quite new to JavaScript, so the code below can be pretty bad. I'm just trying to extract a value from a string. I know parseFloat() would probably not be the solution, but is there any function that would allow for that?
p id="1" would contain some random text and end with a value.
Here below my example:
<div id="abc">
<p id="1">abc 0.99</p>
<p id="2">-</p>
<button onclick="GetValue()">Extract value</button>
</div>
<script>
function GetValue() {
var Value = parseFloat(document.getElementById("1").innerHTML);
document.getElementById("2").innerHTML = Value;
}
</script>
Any suggestion is much appreciated!
The suggestion from this other thread JavaScript get number from string worked, thanks for pointing that out! Updated code:
<div id="abc">
<p id="1">abc 0.99</p>
<p id="2">-</p>
<button onclick="GetValue()">Extract value</button>
</div>
<script>
function GetValue() {
var String = document.getElementById("1").innerHTML;
var Value = String.replace( /^\D+/g, '');
document.getElementById("2").innerHTML = Value;
/*
Solution 2> var Value = String.replace(/^.*?(-?([0-9]+|[0-9]*[.][0-9]+))[ \t]*$/gi,'$1');
Solution 3> var Value = String.match(/\d+(\.\d+)?/)[0];
*/
}
</script>