spliting string except in curly brackets - javascript

I'm trying to split a string on "," but I don't want to split if "," is in "{}". There's no nested braces.
here is the string I want to split :
EmbiBISupplierKPIResult_EditArea00001,EmbiBISupplierKPISearch,partyId=E10021&economicAreaPartyIds={DPP_20246, DPP_14726}&economicId={DPP_20246, DPP_14726}&requestedDateSearchType=ACTUAL_WEEK
Here is the result I expect :
EmbiBISupplierKPIResult_EditArea00001
EmbiBISupplierKPISearch
partyId=E10021&economicAreaPartyIds={DPP_20246, DPP_14726}&economicId={DPP_20246, DPP_14726}&requestedDateSearchType=ACTUAL_WEEK
Is there a regex to do this ?

You can use match and be explicit about the optional matching of parts between braces:
var parts = s.match(/(\{[^{}]*\}|[^,{}]+)+/g)
var s = 'EmbiBISupplierKPIResult_EditArea00001,EmbiBISupplierKPISearch,partyId=E10021&economicAreaPartyIds={DPP_20246, DPP_14726}&economicId={DPP_20246, DPP_14726}&requestedDateSearchType=ACTUAL_WEEK';
var parts = s.match(/(\{[^{}]*\}|[^,{}]+)+/g)
document.querySelector('pre').innerHTML = JSON.stringify(parts,null,'\t');
<pre id=result></pre>

You can use the following:
,(?=(?:[^{}]*{[^{}]*})*[^{}]*$)
See DEMO

Related

String (double quote) formatting in Javascript

I have a string
var st = "asv_abc1_100x101, asv_def2_100x102, asv_ghi1_100x103, asv_jkl4_100x104"
Now I want to put a double quote around each substring
i.e required string
var st = ""asv_abc1_100x101", "asv_def2_100x102", "asv_ghi1_100x103", "asv_jkl4_100x104""
Is this possible to achieve anything like this in javascript?
If you meant to transform a string containing "words" separated by comma in a string with those same "words" wrapped by double quotes you might for example split the original string using .split(',') and than loop through the resulting array to compose the output string wrapping each item between quotes:
function transform(value){
const words = value.split(',');
let output = '';
for(word of words){
output += `"${word.trim()}", `;
}
output = output.slice(0, -2);
return output;
}
const st = "asv_abc1_100x101, asv_def2_100x102, asv_ghi1_100x103, asv_jkl4_100x104";
const output = transform(st);
console.log(output);
That's true unless you just meant to define a string literal containing a character that just needed to be escaped. In that case you had several ways like using single quotes for the string literal or backticks (but that's more suitable for template strings). Or just escape the \" inside your value if you are wrapping the literal with double quotes.
You can use backticks ``
var st = `"asv_abc1_100x101", "asv_def2_100x102", "asv_ghi1_100x103", "asv_jkl4_100x104"`
You can split the string by the comma and space, map each word to a quote-wrapped version of it and then join the result again:
const result = myString
.split(', ')
.map(word => `"${word}"`)
.join(', ')
Also you can transform your string with standard regular expressions:
// String
let st = "asv_abc1_100x101, asv_def2_100x102, asv_ghi1_100x103, asv _ jkl4 _ 100x104";
// Use regular expressions to capture your pattern,
// which is based on comma separator or end of the line
st = st.replace(/(.+?)(,[\s+]*|$)/g, `"$1"$2`);
// Test result
console.log(st);

Need to replace a string from a long string in javascript

I have a long string
Full_str1 = 'ab#xyz.com;cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;c_ab#xyz.com;';
removable_str2 = 'ab#xyz.com;';
I need to have a replaced string which will have
resultant Final string should look like,
cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;c_ab#xyz.com;
I tried with
str3 = Full_str1.replace(new RegExp('(^|\\b)' +removable_str2, 'g'),"");
but it resulted in
cab#xyz.com;c-c.c_ab#xyz.com;
Here a soluce using two separated regex for each case :
the str to remove is at the start of the string
the str to remove is inside or at the end of the string
PS :
I couldn't perform it in one regex, because it would remove an extra ; in case of matching the string to remove inside of the global string.
const originalStr = 'ab#xyz.com;cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;ab#xyz.com;c_ab#xyz.com;';
const toRemove = 'ab#xyz.com;';
const epuredStr = originalStr
.replace(new RegExp(`^${toRemove}`, 'g'), '')
.replace(new RegExp(`;${toRemove}`, 'g'), ';');
console.log(epuredStr);
First, the dynamic part must be escaped, else, . will match any char but a line break char, and will match ab#xyz§com;, too.
Next, you need to match this only at the start of the string or after ;. So, you may use
var Full_str1 = 'ab#xyz.com;cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;c_ab#xyz.com;';
var removable_str2 = 'ab#xyz.com;';
var rx = new RegExp("(^|;)" + removable_str2.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), "g");
console.log(Full_str1.replace(rx, "$1"));
// => cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;c_ab#xyz.com;
Replace "g" with "gi" for case insensitive matching.
See the regex demo. Note that (^|;) matches and captures into Group 1 start of string location (empty string) or ; and $1 in the replacement pattern restores this char in the result.
NOTE: If the pattern is known beforehand and you only want to handle ab#xyz.com; pattern, use a regex literal without escaping, Full_str1.replace(/(^|;)ab#xyz\.com;/g, "$1").
i don't find any particular description why you haven't tried like this it will give you desired result cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;c_ab#xyz.com;
const full_str1 = 'ab#xyz.com;cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;c_ab#xyz.com;';
const removable_str2 = 'ab#xyz.com;';
const result= full_str1.replace(removable_str2 , "");
console.log(result);

Split a string of strings by 2 delimeters

My string looks like
"<!number|Foo bar> <!number|Foo bar> <!number|foo bar>"
I have like to split the string by "<" and ">" so that the new array becomes
["<!number|string>", "<!number|string>" ].
I tried str.split('> <'), which gives me
["<!numer|string", "!number|string>"].
Also I tried using regex to str.split(/\<> /)
which gives me ["<!number|string> <!number|string>"].
How to split it correctly?
At work so I can't fix the nitty gritty with the regex, but the below works given the string
const str = `<!1|Foo bar> <!2|Bar Baz> <!3| xxx yyy>`;
console.log(str.split(/(<[\s\S]*?>)/gm).filter((n)=> { return (n!="" && n!=" ") }));
Just split on space:
let str = "<!number|string> <!number|string> <!number|string>";
console.log(str.split(" "));

Remove consecutive commas with regex

I use
str.replace(/(^,)|(,$)/g, '')
to remove leading and trailing commas.
How can I extend it so I also remove two consecutive commas?
So ,some text,,more text, should become some text,more text?
One way would be to chain with
str.replace(/(^,)|(,$)/g, '').replace(/,,/g, ',')
but then ,some text,,,,more text, will become some text,,more text instead of some text,more text.
Since you appear to be using the str as a source for an array, you can replace all the .replace calls with:
var str = ",some text,,,,more text,";
var resultArray = str.split(',') // Just split the string.
.filter(function(item){ // Then filter out empty items
return item !== '';
});
console.log(resultArray)
No need to worry about leading, trailing or double comma's.
Remove the leading and trailing commas, and then replace multiple consecutive commas by single comma
str.replace(/^,|,$|(,)+/g, '$1');
,+ will match one or more comma, g-global flag to replace all occurrences of it.
var str = ',some text,,more text,';
str = str.replace(/^,|,$|(,)+/g, '$1');
console.log(str);
You may add an alternative branch and enclose it with a capturing group and then use a replace callback method where you can analyze the match groups and perform the replacement accordingly:
var s = ',some text,,,,more text,';
var res = s.replace(/^,|,$|(,+)/g, function(m,g1) {
return g1 ? ',' : '';
});
console.log(res);
To split with commas and get no empty entries in the resulting array, use a simple
console.log(',some text,,,,more text,'.split(',').filter(Boolean));
You could add a positive lookahead with another comma.
var str = ',some text,,more text,';
str = str.replace(/^,|,$|,(?=,)/g, '')
console.log(str);
What about one replace only like: ",some text,,,,more text,".replace(/(^,)|(,$)|,(?=,)/g, '');
[EDIT]
Note that lookbehinds don't work in javascript. so you can only use a lookahead like so.

Simple regex replace brackets

Is there an easy way to make this string:
(53.5595313, 10.009969899999987)
to this String
[53.5595313, 10.009969899999987]
with JavaScript or jQuery?
I tried with multiple replace which seems not so elegant to me
str = str.replace("(","[").replace(")","]")
Well, since you asked for regex:
var input = "(53.5595313, 10.009969899999987)";
var output = input.replace(/^\((.+)\)$/,"[$1]");
// OR to replace all parens, not just one at start and end:
var output = input.replace(/\(/g,"[").replace(/\)/g,"]");
...but that's kind of complicated. You could just use .slice():
var output = "[" + input.slice(1,-1) + "]";
For what it's worth, to replace both ( and ) use:
str = "(boob)";
str = str.replace(/[\(\)]/g, ""); // yields "boob"
regex character meanings:
[ = start a group of characters to look for
\( = escape the opening parenthesis
\) = escape the closing parenthesis
] = close the group
g = global (replace all that are found)
Edit
Actually, the two escape characters are redundant and eslint will warn you with:
Unnecessary escape character: ) no-useless-escape
The correct form is:
str.replace(/[()]/g, "")
var s ="(53.5595313, 10.009969899999987)";
s.replace(/\((.*)\)/, "[$1]")
This Javascript should do the job as well as the answer by 'nnnnnn' above
stringObject = stringObject.replace('(', '[').replace(')', ']')
If you need not only one bracket pair but several bracket replacements, you can use this regex:
var input = "(53.5, 10.009) more stuff then (12) then (abc, 234)";
var output = input.replace(/\((.+?)\)/g, "[$1]");
console.log(output);
[53.5, 10.009] more stuff then [12] then [abc, 234]

Categories