javascript 如何在javascript中的两个分隔符之间拆分字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13594241/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 19:13:09  来源:igfitidea点击:

How to split string between two separators in javascript?

javascripthtmlarraysregexstring

提问by curious-cat

I know how to split using, multiple separators but I have no idea how to split a string into an array betweentwo characters. So:

我知道如何使用多个分隔符进行拆分,但我不知道如何将字符串拆分为两个字符之间的数组。所以:

var myArray = "(text1)(text2)(text3)".split(???)
//=> myArray[0] = "text1", myArray[1] = "text2", myArray[2] = "text3"

What should I enter in the "???"? Or is there a different approach I should use?

我应该在“???”中输入什么?或者我应该使用不同的方法吗?

Making ")(" a separator won't work as I want to split the array with a variety of separators such as ">" making it very unpractical to list every possible combination of separators

使 ")(" 分隔符不起作用,因为我想用各种分隔符(例如“>”)拆分数组,这使得列出所有可能的分隔符组合非常不切实际

采纳答案by ?mega

.split(/[()]+/).filter(function(e) { return e; });

See this demo.

请参阅此演示

回答by Martin Ender

Using split between specific characters without losing any characters is not possible with JavaScript, because you would need a lookbehind for that (which is not supported). But since you seem to want the texts insidethe parentheses, instead of splitting you could just matchthe longest-possible string not containing parentheses:

JavaScript 无法在不丢失任何字符的情况下使用特定字符之间的拆分,因为您需要对此进行后视(不支持)。但既然你似乎想在文本括号,而不是分裂你可能只是match时间最长的可能的字符串不含括号:

myArray = "(text1)(text2)(text3)".match(/[^()]+/g)