Javascript 从字符串中提取(“获取”)一个数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10003683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Extract ("get") a number from a string
提问by user1022585
I have a string in javascript like `#box2' and I just want the '2' from it.
我在 javascript 中有一个字符串,比如 `#box2',我只想要它的 '2'。
Tried:
尝试:
var thestring = $(this).attr('href');
var thenum = thestring.replace( /(^.+)(\w\d+\w)(.+$)/i,'');
alert(thenum);
It still returns #box2 in the alert, how can I get it to work?
它仍然在警报中返回 #box2,我怎样才能让它工作?
It needs to accommodate for any length number attached on the end.
它需要适应末端附加的任何长度数字。
回答by georg
For this specific example,
对于这个特定的例子,
var thenum = thestring.replace( /^\D+/g, ''); // replace all leading non-digits with nothing
in the general case:
在一般情况下:
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>
回答by Jason Marshall
You should try the following:
您应该尝试以下操作:
var txt = "#div-name-1234-characteristic:561613213213";
var numb = txt.match(/\d/g);
numb = numb.join("");
alert (numb);?
result
结果
1234561613213213
回答by Theodoros Klikas
I think this regular expression will serve your purpose:
我认为这个正则表达式将满足您的目的:
var num = txt.replace(/[^0-9]/g,'');
Where txt
is your string.
txt
你的字符串在哪里。
It basically rips off anything that is not a digit.
它基本上撕掉了任何不是数字的东西。
I think you can achieve the same thing by using this as well :
我认为您也可以通过使用它来实现相同的目的:
var num = txt.replace(/\D/g,'');
回答by xbalaji
Try the following: string.replace(/[^0-9]/g, '');
This will delete all non-digit characters, leaving only digits in the string
尝试以下操作:string.replace(/[^0-9]/g, '');
这将删除所有非数字字符,只留下字符串中的数字
function retnum(str) {
var num = str.replace(/[^0-9]/g, '');
return parseInt(num,10);
}
console.log('abca12bc45qw'.replace(/[^0-9]/g, ''));
console.log('#box2'.replace(/[^0-9]/g, ''));
回答by Shiplu Mokaddim
回答by Paulo Roberto Rosa
Tried all the combinations cited abovewith this Code and got it working, was the only one that worked on that string -> (12) 3456-7890
使用此代码尝试了上面引用的所有组合并使其正常工作,是唯一可以处理该字符串的组合->(12) 3456-7890
var str="(12) 3456-7890";
str.replace( /\D+/g, '');
Result:"1234567890"
结果:"1234567890"
Obs:i know that a string like that will not be on the attr but whatever, the solution is better, because its more complete.
Obs:我知道这样的字符串不会出现在 attr 上,但无论如何,解决方案更好,因为它更完整。
回答by Lacho Tomov
And this is a snippet which extracts prices with currency and formatting:
这是一个使用货币和格式提取价格的片段:
var price = "£1,739.12";
parseFloat(price.replace( /[^\d\.]*/g, '')); // 1739.12
回答by Eugene Tiurin
you may use great parseInt method
你可以使用很棒的 parseInt 方法
it will convert the leading digits to a number
它将前导数字转换为数字
parseInt("-10px");
// will give you -10
回答by icyrock.com
For a string such as #box2
, this should work:
对于诸如 的字符串#box2
,这应该有效:
var thenum = thestring.replace(/^.*?(\d+).*/,'');
jsFiddle:
js小提琴:
回答by Robby Shaw
You can use regular expression.
您可以使用正则表达式。
var txt="some text 2";
var numb = txt.match(/\d/g);
alert (numb);
That will alert 2.
这将提醒 2。