JavaScript Split around curly braces

前端 未结 5 2131
再見小時候
再見小時候 2021-02-09 09:40

I have a string format inside of a string variable:

\"{0} Hello World {1}\"

I need to split it into something like this:

\"{0}\         


        
5条回答
  •  醉话见心
    2021-02-09 10:21

    You can use Split with a regex having capturing group(s):

    If separator is a regular expression that contains capturing parentheses, then each time separator is matched, the results (including any undefined results) of the capturing parentheses are spliced into the output array.

    var re = /\s*(\{[0-9]+\})\s*/g;
    var splt = "{0} Hello World {1}".split(re).filter(Boolean);
    alert(splt);

    Regex explanation:

    • \s* - Any number of whitespaces
    • (\{[0-9]+\}) - A capturing group that matches:
      • \{ - a literal {
      • [0-9]+ - 1 or more digits
      • \} - a literal }
    • \s* - Any number of whitespaces

    filter can help get rid of empty elements in the array.

    filter() calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback returns a true value or a value that coerces to true. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.

    Array elements which do not pass the callback test are simply skipped, and are not included in the new array.

提交回复
热议问题