JavaScript で文字列から数値を抽出するにはどうすればいいですか? 質問する

JavaScript で文字列から数値を抽出するにはどうすればいいですか? 質問する

JavaScript に文字列 (例: ) があり#box22そこから を取得したいだけです。

私は試した:

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

まだ#box2アラートが返されます。どうすれば動作させることができますか?

端に付いている長さの数字に対応する必要があります。

ベストアンサー1

この特定の例では、

 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>

おすすめ記事