代码之家  ›  专栏  ›  技术社区  ›  Alex

javascript/jquery-从字符串中获取数字

  •  12
  • Alex  · 技术社区  · 14 年前

    绳子看起来像这样

    "blabla blabla-5 amount-10 blabla direction-left"
    

    我怎么才能在刚过的时候拿到号码 "amount-" 和后面的文字 "direction-" ?

    3 回复  |  直到 11 年前
        1
  •  17
  •   PleaseStand    14 年前

    这种用途 regular expressions 以及 exec method :

    var s = "blabla blabla-5 amount-10 blabla direction-left";
    var amount = parseInt(/amount-(\d+)/.exec(s)[1], 10);
    var direction = /direction-([^\s]+)/.exec(s)[1];
    

    如果缺少数量或方向,代码将导致错误;如果可能,请在索引到应返回的数组之前检查exec的结果是否为非空。

        2
  •  38
  •   Aniket Kulkarni    11 年前

    这将得到用昏迷隔开的所有数字:

    var str = "10 is smaller than 11 but greater then 9";
    var pattern = /[0-9]+/g;
    var matches = str.match(pattern);
    

    执行后,字符串 matches 将具有值 "10,11,9"

    如果您只是在寻找第一个出现的W,模式将是 /[0-9]+/ -哪个会回来 10

    (不需要jquery)

        3
  •  6
  •   Aif    14 年前

    您可以按照说明使用regexp by w3schools . 提示:

    str = "blabla blabla-5 amount-10 blabla direction-left"
    alert(str.match(/amount-([0-9]+)/));
    

    另外,你可以简单地想要所有的数字,所以只使用模式[0-9]+。 str.match将返回一个数组。