我有一个JavaScript字符串(例如,#box2),我只是想从它的2。

我试着:

var thestring = $(this).attr('href');
var thenum = thestring.replace(/(^.+)(\w\d+\w)(.+$)/i, '$2');
alert(thenum);

它仍然在警告中返回#box2。我怎样才能让它工作呢?

它需要适应任何长度的数字附着在末端。


当前回答

您需要添加“(/\d+/g)”,这将删除所有非数字文本,但它仍然是一个字符串。如果您通过匹配创建了一个变量和“parseInt”,您可以将新变量设置为数组值。下面是我如何让它工作的一个例子:

    var color = $( this ).css( "background-color" );
    var r = parseInt(color.match(/\d+/g)[0]);
    var g = parseInt(color.match(/\d+/g)[1]);
    var b = parseInt(color.match(/\d+/g)[2]);

其他回答

试试下面的:string。替换(/ [^ 0 - 9]/ g,”);这将删除所有非数字字符,在字符串中只留下数字

function retnum(str) { 
    var num = str.replace(/[^0-9]/g, ''); 
    return parseInt(num,10); 
}

console.log(“abca12bc45qw”。替换(/ [^ 0 - 9]/ g, ")); console.log(“# box2”。替换(/ [^ 0 - 9]/ g, "));

对于这个具体的例子,

 var thenum = thestring.replace(/^\D+/g, ''); // Replace all leading non-digits with nothing

一般情况下:

 thenum = "foo3bar5".match(/\d+/)[0] // "3"

这里有一个奖励:正则表达式生成器。

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>

let str = "Total Work Duration: 189.56 Hrs.Present: 23.5 Absent: 2";

/* The provided regex globally matches the character
   "." and a digit from the string */
let numArr = str.match(/[\d\.]+/g)

/* It returns an array [189.56, ., 23.5, 2], and
   uses the filter function to remove the '.' */
numArr = numArr.filter(n => n != '.')
console.log(numArr)

使用匹配函数。

var thenum = “0a1bbb2”.match(/\d+$/)[0]; console.log(thenum);

你可以像下面这样使用Underscore.js的字符串库:

var common = "#box"
var href = "#box1"

_(href).strRight(common)

结果将是:1

看:Underscore.string

演示:

http://jsfiddle.net/abdennour/Vyqtt/

HTML代码:

<p>
    <a href="#box1" >img1</a>
    <a href="#box2" >img2</a>
    <a href="#box3" >img3</a>
    <a href="#box4" >img4</a>
</p>
<div style="font-size:30px"></div>

JavaScript代码:

var comm = "#box"
$('a').click(function() {
  $('div').html(_($(this).attr('href')).strRight(comm))})

如果你有如下后缀:

href="box1az"

您可以使用以下演示:

http://jsfiddle.net/abdennour/Vyqtt/1/

function retrieveNumber(all, prefix, suffix) {
  var left = _(all).strRight(prefix);
  return _(left).strLeft(suffix);
}