Split string and keep the separator

后端 未结 2 1022
[愿得一人]
[愿得一人] 2021-01-25 23:38

I\'m writing a chrome extension, and I need to split a string that contains only text and img tags, so that every element of the array is either letter or img tag. For example,

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-26 00:04

    The reason you get empty elements is the same why you get inyour results. When you use capturing parentheses in a split pattern, the result will contain the captures in the places where the delimiters were found. Since you have (|), you match (and capture) an empty string if the second alternative is used. Unfortunately, ()| alone doesn't help, because you'll still get undefined instead of empty strings. However, you can easily filter those out:

    str.split(/(]*>)|/).filter(function(el) { return el !== undefined; });
    

    This will still get you empty elements at the beginning and the end of the string as well as between adjacent tags, though. So splitting would result in

    ["", "", "", "", ""]
    

    If you don't want that, the filter function becomes even simpler:

    str.split(/(]*>)|/).filter(function(el) { return el; });
    

提交回复
热议问题