最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Extract value from string in JavaScript - Stack Overflow

programmeradmin2浏览0评论

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>

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>
Share Improve this question edited Sep 21, 2017 at 20:09 M_B asked Sep 21, 2017 at 19:10 M_BM_B 131 gold badge1 silver badge4 bronze badges 3
  • 1 Is it always separated by space? If so you could just split innerText and select the last array item – lumio Commented Sep 21, 2017 at 19:12
  • try this stackoverflow./questions/10003683/… – user1844933 Commented Sep 21, 2017 at 19:14
  • Possible duplicate of JavaScript get number from string – pucky124 Commented Sep 21, 2017 at 19:20
Add a ment  | 

4 Answers 4

Reset to default 3

You can use following regex:

var str = "abc 0.99";
let number=str.match(/\d+(\.\d+)?/)[0];
alert(number);

Regex Explanation

  • 0-9 : Matches any number
  • . : Matches . literal
  • + : Matches previous group one or more time

When the structure of your string is always like "textspacenumber" where number is always at the end, you could just split the string and use the last item:

const str = "abc 0.99";
const tokens = str.split( ' ' );
const number = parseFloat( tokens[ tokens.length - 1 ] );
console.log( number );

This is way simpler than using RegEx (which is fine too, but slower)

parseFloat is fine, if you really need the numerical value. The "some random text and end with a value" part can be a bit tricker, depending on what that text can be. (for example can it contain other numbers?)

Here's a way to do it with regular expressions:

var s = document.getElementById('1').innerHTML;
s = s.replace(/^.*?(-?([0-9]+|[0-9]*[.][0-9]+))[ \t]*$/gi,'$1');
var x = parseFloat(s);
document.getElementById('2').innerHTML = x;

Explanation of the 2nd line: this is a regular expression that extracts a numerical part from the end of a string. A 'numerical part' here may start with a minus sign (for negative numbers), and then either just a bunch of digits (for integer values), or zero or more digits followed by a decimal point followed by one or more decimals. I've added [ \t]* to also allow for some optional whitespace at the end.

This can look pretty crazy if you're not familiar with regular expressions.

By the way, since you're only putting the result back into your HTML content, there is actually no need for parseFloat. You can just put the resulting s (which is still a string but only the number, with the content before number stripped away) straight back into the HTML.

If you are doing actual calculations with the number, then yes, use parseFloat(s).

Try this:

function GetValue() {
    var myValue = document.getElementById("1").textContent;
    document.getElementById("2").innerHTML = myValue;
}

Note: You were trying to assign value to a system variable - Value.

Code runing: https://jsfiddle/2ohf65hc/

发布评论

评论列表(0)

  1. 暂无评论