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?
source to share
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);
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 reachtrue
. 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.
source to share
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);
source to share
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.
source to share