如何从 JavaScript 中的字符串中提取数字? [英] How can I extract a number from a string in JavaScript?
本文介绍了如何从 JavaScript 中的字符串中提取数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 JavaScript 中有一个字符串(例如 #box2
),我只想要它的 2
.
I have a string in JavaScript (e.g #box2
) and I just want the 2
from it.
我试过了:
var thestring = $(this).attr('href');
var thenum = thestring.replace( /(^.+)(wd+w)(.+$)/i,'$2');
alert(thenum);
它仍然在警报中返回 #box2
,我怎样才能让它工作?
It still returns #box2
in the alert, how can I get it to work?
它需要适应末尾附加的任何长度数字.
It needs to accommodate for any length number attached on the end.
推荐答案
对于这个特定的例子,
var thenum = thestring.replace( /^D+/g, ''); // replace all leading non-digits with nothing
一般情况下:
thenum = "foo3bar5".match(/d+/)[0] // "3"
由于这个答案出于某种原因广受欢迎,这里有一个奖励:正则表达式生成器.
Since this answer gained popularity for some reason, here's a bonus: regex generator.
function getre(str, num) {
if(str === num) return 'nice try';
var res = [/^D+/g,/D+$/g,/^D+|D+$/g,/D+/g,/D.*/g, /.*D/g,/^D+|D.*$/g,/.*D(?=d)|D+$/g];
for(var i = 0; i < res.length; i++)
if(str.replace(res[i], '') === num)
return 'num = str.replace(/' + res[i].source + '/g, "")';
return 'no idea';
};
function update() {
$ = function(x) { return document.getElementById(x) };
var re = getre($('str').value, $('num').value);
$('re').innerHTML = 'Numex speaks: <code>' + re + '</code>';
}
<p>Hi, I'm Numex, the Number Extractor Oracle.
<p>What is your string? <input id="str" value="42abc"></p>
<p>What number do you want to extract? <input id="num" value="42"></p>
<p><button onclick="update()">Insert Coin</button></p>
<p id="re"></p>
这篇关于如何从 JavaScript 中的字符串中提取数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文