简体   繁体   English

如何获得多个子字符串的数组,该数组由Javascript中的相同字符串/符号/标签除

[英]How to get an array of multiple substrings divided by the same string/symbol/tag in Javascript

I have a string that is composed of different elements and I need to separate them at another tag in the string. 我有一个由不同元素组成的字符串,我需要在字符串的另一个标签处将它们分开。

I used .split() and .pop() which worked great if there is only one element. 我使用了.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'

However, I have now encountered multiple elements and in this case it only returns the last element. 但是,我现在遇到了多个元素,在这种情况下,它仅返回最后一个元素。


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

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

How do I get an array with all the substrings between those tags? 如何获得带有这些标签之间所有子字符串的数组?

 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) 

You can use shift() to remove first element and then use map() 您可以使用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')) 

The reason why you're getting the last element is because you're using pop() which just returns the last element in array: 之所以要获取最后一个元素,是因为您使用的pop()仅返回数组中的最后一个元素:

The pop() method removes the last element from an array and returns that element. pop()方法从数组中删除最后一个元素,然后返回该元素。 This method changes the length of the array. 此方法更改数组的长度。

You can read more about it on here website 您可以在这里的网站上了解更多信息

Here's one way to do it. 这是一种方法。

 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' 

Explaining: 说明:

// 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(/\*$/, ''));

EDIT 编辑

Reading @junvar's answer I noticed a pattern that I haven't noticed when I answered. 阅读@junvar的答案时,我注意到我回答时没有注意到的模式。 That if you substitute * by < or > you have a XML pattern. 如果用*替换<或>,则表示XML模式。 So it seems to me that the OP has replaced < and > by * in order to mask this is XML parsing. 因此,在我看来,OP用*代替了<和>以掩盖XML解析。 If it is a XML parse, please read the most famous answer in SO: 如果是XML解析,请阅读SO中最著名的答案:

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

JUST DON'T PARSE XML WITH REGEX. 只是不要使用REGEX解析XML。

Using pop() returns the last element in an array(the array that is created when you do your first split) 使用pop()返回数组中的最后一个元素(第一次拆分时创建的数组)

try: 尝试:

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'));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM