JavaScript Separating curly braces

I have a string format inside a string variable:

"{0} Hello World {1}"

      

I need to break it down into something like this:

"{0}","Hello World","{1}"

      

From what I've tried, I could do better:

"","0"," Hello World ","1",""

      

I tried converting the examples from Split cues around curly braces but that didn't work, the split there either removed everything, or kept the spaces and removed {}

.

So my questions are the same as in the other article, how do I keep the curly braces {}

and remove spaces after and before not between words?

+3


source to share


5 answers


You can use Split

with regex having capturing group (s)
:

If the delimiter is a regular expression that contains a capturing parenthesis, then each time the delimiter is matched, the results (including any undefined results) of the sliding 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);
      

Run codeHide result




Regex explanation:

  • \s*

    - any number of spaces
  • (\{[0-9]+\})

    - a capture group that matches:
    • \{

      - literal {

    • [0-9]+

      - 1 or more digits
    • \}

      - literal }

  • \s*

    - any number of spaces

filter

can help get rid of empty elements in an array.

filter()

calls the provided callback function once for each element in the array and creates a new array from all values โ€‹โ€‹for which the callback returns a true value or a value that is forced to reach true

. the callback is called only for array indices that are assigned values; it is not called for indexes that have been dropped or that have never been assigned a value.

Array elements that fail the callback test are simply skipped and not included in the new array.

+4


source


You can use the following:

\s*({\d+})\s*

      

JS code:



var regex = /\s*({\d+})\s*/g;
var split_string = "{0} Hello World {1}".split(regex).filter(Boolean);
alert(split_string);
      

Run codeHide result


+3


source


You can do the following:

var myregexp = /({.*?})(.*?)({.*?})/im;
var match = myregexp.exec(subject);
   if (match != null) 
   {
     result1 = match[1];
     result2 = match[2];
     result3 = match[3];
   }

      

0


source


You can just filter out empty lines if you like:

var s = "{0} Hello World {1}";
s.split(/({\d+})/).filter(Boolean);

      

which returns

["{0}", " Hello World ", "{1}"]

      

0


source


var myString = "{0} Hello World {1}"
var splits = myString.split(/\s?{\d}\s?/);

      

which will return ["," Hello World "," "],

var count = 0;
for (var i=0; i< splits.length; i++) {
    if (splits[i] === "") {
        splits[i] = "{" + count + "}";
        count++;
    }
}

      

now the splits will have what you need.

0


source







All Articles