【问题标题】:How to get an array of multiple substrings divided by the same string/symbol/tag in Javascript如何在Javascript中获取多个子字符串的数组除以相同的字符串/符号/标签
【发布时间】:2019-04-26 15:12:25
【问题描述】:

我有一个由不同元素组成的字符串,我需要在字符串中的另一个标记处将它们分开。

我使用了 .split() 和 .pop() 如果只有一个元素,它们会很好用。

function getText(fullText, type) {

    var partial = fullText.split('*' + type + '*').pop().split('*/' + type + '*')[0] || 'unknown';
    return partial;
}

var str = "*a*Substring A*/a**b*Substring B*/b**c*Substring C*/c*"

getText(str, a)  // returns 'Substring A'

但是,我现在遇到了多个元素,在这种情况下它只返回最后一个元素。


var str = "*a*Substring A*/a**b*Substring B1*/b**b*Substring B2*/b*"

getText(str, b)  // returns 'Substring B2'

如何获得一个包含这些标签之间所有子字符串的数组?

【问题讨论】:

    标签: javascript string substring


    【解决方案1】:

    function getText(fullText, type) {
        let re = `\\*${type}\\*(.*?)\\*/${type}\\*`;
        return fullText
          .match(new RegExp(re, 'g'))
          .map(str => str.match(new RegExp(re))[1]);
    }
    
    var str = "*a*Substring A*/a* woah *a*Substring A 2*/a*"
    
    x = getText(str, 'a') 
    
    console.log(x)

    【讨论】:

    • RegExp 非常适合这个解决方案 +1。
    • 这是一个优雅的解决方案,但我正在使用带有 indesign 的 jsx 准确地说,它似乎不支持 es6s 映射,因为它返回“错误字符串:> 没有值”我可以这样做有什么不同吗?
    • map 只是传统 for 循环的语法糖。你可以这样替换它。例如for (let i = 0; i < fullText.length; i++) fullText[i] = str.match(...);
    【解决方案2】:

    您可以使用shift() 删除第一个元素,然后使用map()

    function getText(fullText, type) {
    
        var partial = fullText.split('*' + type + '*') 
        partial.shift();
        for(let i = 0;i<partial.length;i++){
          partial[i] = partial[i].split('*/' + type + '*')[0]
        }
        return partial
    }
    
    var str = "*a*Substring A*/a**b*Substring B1*/b**b*Substring B2*/b*"
    
    console.log(getText(str, 'b'))

    【讨论】:

    • 这看起来也很整洁,但正如我在另一条评论中提到的那样,我正在使用带有 indesign 的 jsx,准确地说,它似乎不支持 es6s 映射,因为它返回“错误字符串:>没有价值'我可以这样做吗?
    • @GabrielRodaEugenBach 是否支持forEach()
    • @GabrielRodaEugenBach 我已将map() 替换为for 循环。一定要检查一下。
    【解决方案3】:

    你得到最后一个元素的原因是因为你使用了pop(),它只返回数组中的最后一个元素:

    pop() 方法从数组中删除最后一个元素并返回该元素。这个方法改变了数组的长度。

    您可以在here 网站上阅读更多信息

    【讨论】:

      【解决方案4】:

      使用 pop() 返回数组中的最后一个元素(第一次拆分时创建的数组)

      尝试:

      function getText(fullText, type) {
              var partial = fullText.split('*' + type + '*');
              var result = [];
                  $.each(partial, function(i, item) {
                       var split = item.split('*/' + type + '*');
                       if (split.length > 1) {
                            result.push(split[0]);
                       }
                  });
                   return result;
              }
              var str = "*a*Substring A*/a**b*Substring B1*/b**b*Substring B2*/b*";
              console.log(getText(str, 'b'));
      

      【讨论】:

        【解决方案5】:

        这是一种方法。

        function getText(fullText, type) {
            var typeStr = "\*" + type + "\*";
            return fullText
                .split('/')
                .filter(item=>item.match(typeStr.replace(/\*/g, '\\*')))
                .map(item=>item
                    .substr(item.indexOf(typeStr) + typeStr.length)
                    .replace(/\*$/, ''));
        }
        
        var str = "*a*Substring A*/a**b*Substring B*/b**c*Substring C*/c*"
        
        console.log(getText(str, 'a'));  // returns 'Substring A'
        
        var str = "*a*Substring A*/a**b*Substring B1*/b**b*Substring B2*/b*"
        
        console.log(getText(str, 'b'));  // returns 'Substring B2'

        解释:

        // this creates a str with the type to be searched
        var typeStr = "\*" + type + "\*";
        return fullText
            // this splits all elements in your string
            .split('/')
            // this leaves only elements that match type...
            .filter(item=>item.match(
                // using a regex created with the typeStr created above
                // replace escape the * char to make regex work
                typeStr.replace(/\*/g, '\\*')))
            // now with the remaining parts, alter them as follows...        
            .map(item=>item
                // remove everything before type and type itself
                .substr(item.indexOf(typeStr) + typeStr.length)
                // remove last * char
                .replace(/\*$/, ''));
        

        编辑

        阅读@junvar 的回答时,我注意到了一个我在回答时没有注意到的模式。如果您将 * 替换为 ,您就有了 XML 模式。因此,在我看来,OP 已将 替换为 * 以掩盖这是 XML 解析。如果是 XML 解析,请阅读 SO 中最著名的答案:

        https://stackoverflow.com/a/1732454/2752520

        不要使用正则表达式解析 XML。

        【讨论】:

          猜你喜欢
          • 2017-08-28
          • 1970-01-01
          • 2020-01-25
          • 1970-01-01
          • 2016-05-12
          • 2015-09-08
          • 1970-01-01
          • 2019-07-07
          相关资源
          最近更新 更多