【问题标题】:is there an elegant way to extract the words from this array ["{ test1, test2 }", "test3", "{test4, test5}"], and put them together inside one array?有没有一种优雅的方法可以从这个数组 ["{ test1, test2 }", "test3", "{test4, test5}"] 中提取单词,并将它们放在一个数组中?
【发布时间】:2017-06-01 02:36:08
【问题描述】:

基本上我想把数组从

["{ test1, test2 }", "test3", "{test4, test5}"]

["test1","test2","test3","test4","test5"]

我正在使用正则表达式,matchTest 是保存正则表达式的变量,用于匹配单词并使用匹配项填充此数组,并将数组固定在同一循环中。

 while (regexMatches = matchTest.exec(sourceCode)) {
   testArray.push(regexMatches[1].replace(/\W/g, " ").split(" "));
   testArray = [].concat(...testArray);
   testArray = testArray.filter(testArray => testArray != '');
 }

我这样做的方式很有效,但看起来很混乱。任何有关如何改进这一点的帮助将不胜感激。

【问题讨论】:

    标签: javascript arrays regex


    【解决方案1】:
    var array = ["{ test1, test2 }", "test3", "{test4, test5}"];
    var output = array.join(',').replace(/[^\w,]/g,'').split(',');
    

    【讨论】:

    • 其实这个 /[^\w,]/g 来自你的解决方案,呵呵
    【解决方案2】:

    我会使用.reduce() 如下:

    var input = ["{ test1, test2 }", "test3", "{test4, test5}"]
    
    var output = input.reduce((acc, v) => {
      acc.push(...v.replace(/[^\w,]/g,"").split(","))
      return acc
    }, [])
    
    console.log(output)

    即对数组中的每一项,先去掉所有不是单词字符或逗号的字符,然后按逗号分割,然后将结果压入输出数组。

    【讨论】:

      【解决方案3】:

      你应该把match

      var string = '["{ test1, test2 }", "test3", "{test4, test5}"]';
      var array = string.match(/\w+\d+/g);
      console.log(array);

      【讨论】:

        猜你喜欢
        • 2017-11-07
        • 1970-01-01
        • 1970-01-01
        • 2021-03-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-01
        相关资源
        最近更新 更多