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

如何在javascript中从字符串中提取特定数据?

  •  -1
  • DevMike  · 技术社区  · 8 年前

    我的字符串将始终以以下格式返回,其中数字表示我需要瞄准的不断变化的变量:

    params:string = "a random description here followed by a space and then this #gruser4upload #gruser15cat #gruser23camp"
    

    我如何提取号码?

    upload = 4
    cat = 15
    camp = 23
    

    我试过使用如下方法,但由于 #gruser 存在于我的三个目标中。

    let upload = params.substring(
                  params.lastIndexOf("#gruser") + 1, 
                  params.lastIndexOf("upload")
                );
    
    1 回复  |  直到 6 年前
        1
  •  4
  •   CertainPerformance    8 年前

    使用正则表达式捕获后跟字母字符的数字,然后提取每个组:

    const params = "a random description here followed by a space and then this #gruser4upload #gruser15cat #gruser23camp";
    let match;
    const re = /(\d+)([a-z]+)/gi;
    while (match = re.exec(params)) {
      console.log(match[1] + ' : ' + match[2]);
    }