从字符串中提取(“获取”)一个数字

    技术2023-08-04  87

    本文翻译自:Extract (“get”) a number from a string

    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,'$2'); 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. 它需要适应末端附加的任何长度编号。


    #1楼

    参考:https://stackoom.com/question/fyPj/从字符串中提取-获取-一个数字


    #2楼

    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>


    #3楼

    For a string such as #box2 , this should work: 对于#box2这样的字符串,这应该有效:

    var thenum = thestring.replace(/^.*(\d+).*$/i,'$1');

    jsFiddle: 的jsfiddle:

    http://jsfiddle.net/dmeku/ http://jsfiddle.net/dmeku/

    #4楼

    Using match function. 使用匹配功能。

    var thenum = thestring.match(/\d+$/)[0]; alert(thenum);

    jsfiddle 的jsfiddle


    #5楼

    You can use regular expression. 您可以使用正则表达式。

    var txt="some text 2"; var numb = txt.match(/\d/g); alert (numb);

    That will alert 2. 这将提醒2。


    #6楼

    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
    Processed: 0.009, SQL: 9