Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Split around curly braces

I have a string format inside of a string variable:

"{0} Hello World {1}"

I need to split it into something like this:

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

From what I have tried the best I could get was:

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

I have tried converting the examples from Regex Split Around Curly Braces but it did not work, the split there either deleted everything or kept the spaces and removed the {}.

So, my questions is the same as in the other article, how do I keep the braces {} and remove spaces after and before them not in between the words?

like image 936
Danielok1993 Avatar asked Jun 01 '15 14:06

Danielok1993


People also ask

How do you split brackets in JavaScript?

If you need to also split on a space, you can add a space between the square brackets. Copied! const str = 'a.b c'; const result = str. split(/[. ]/); // 👇️ ['a', 'b', 'c'] console.

Does JavaScript need curly braces?

Yes, it works, but only up to a single line just after an 'if' or 'else' statement. If multiple lines are required to be used then curly braces are necessary.

What do double curly brackets mean in JavaScript?

Creating and executing a simple template Handlebars expressions are put into double curly braces {{expr}} for HTML-escaped content; otherwise, use triple curly brackets {{{expr}}} to avoid HTML-escaping.

Is there a split in JavaScript?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.


Video Answer


1 Answers

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.

like image 120
Wiktor Stribiżew Avatar answered Sep 26 '22 01:09

Wiktor Stribiżew