javascript split method comma but without double quotes - javascript

I have a string and want to split it by comma , but my string also has "," which I want ignored, so in short I want to split only where there's , without double quotes.
This is the code I'm testing it with
function splitByCommas(str) {
return str.split(/,(?=(?:[:""]*"[^"]*")*[^"]*$)/);
}
Results from the function above:
console.log(splitByCommas('gango.cs.{"test","asfasf"},ratings.eq.5,name.eq.kings}'));
What the function outputs [ 'gango.cs.{"test"', '"asfasf"}', 'ratings.eq.5', 'name.eq.kings}' ]
My desired output [ 'gango.cs.{"test","asfasf"}', 'ratings.eq.5', 'name.eq.kings}' ]
Anyone might have a hint on how to get my desired output?

Use /(?<!"),(?!")/ regex.
I've tested and confirmed the following code is working.
function splitByCommas(str) {
return str.split(/(?<!"),(?!")/);
}

Related

Why is my JavaScript output weird when I am implementing .match regex?

So, i been getting this kind of output lately when im coding but i just want to make sure its normal or maybe im doing something wrong. Here is a simple code.. maybe it has to do with regex.
my console says " (1) ['a', index: 1, input: 'karina', groups: undefined] "
function reg(s) {
reg = /[aeiou]/;
console.log(s.match(reg));
}
reg("turtle");
Your code is working just fine. The .match() method will compare the string and the RegEx that you defined and return an array with the first match it finds and at what index it happens.
If you want to get back an array with all of the results and without the other information, all you need to do is add a "g" at the end of your RegEx. Your function should look like this:
function reg(s) {
reg = /[aeiou]/g;
console.log(s.match(reg));
}
reg('turtle');
The "g" at the end, will make so that .match() will look and grab all of the occurrences in the string that you are checking, instead of just the first one.

Removing [ and ] from xmlhttp array javascript variable

I have seen many of these examples but I just cant seem to get it to work.
I have ["15"], and want to remove the ["] and just leave the number.
I have removed the " using
pickupsuburbcode = pickupsuburbcode.replace(/['"]/g, '');
so now I have [15]
but now I am stuck.
Just include [ and ] inside your regex character class, with proper escaping
'["15"]'.replace(/['"[\]]/g, ''); // '15'
Instead of thinking about this as removing the [ and ", think about it as picking out the numbers.
var match = '["15"]'.match(/\d+/);
console.log(match[0]);
But why are you trying to do this? If this is JSON, don't try to parse it using regexp. Instead, just parse it and extract what you want:
var result = JSON.parse('["15"]');
console.log(Number(result[0]));

I need match string in quotes

I need to match string within "" , I'm using following it's not working
var str='"hi" hello "abc\nddk" ef "gh"';
console.log(str.match(/(?=")[^"]*?(?=")/));
t's giving me output as
[]
I need output as
["hi", "abc\nddk", "gh"]
Update :
I can use regex "[^"]" to match string in quotes but I need to avoid the " from the result
Simplest way would be to do:
/"[^"]*?"/g
This will return an array with "hi", "abc\nddk" and "gh" and you can do something like piece.replace(/"/g, "") on individual pieces to get rid of the ". If you don't like that then rather than do a match you can do a search and don't replace
var matches = [];
str.replace(/"([^"]*?)"/g, function (_, match) {
matches.push(match);
});
This should do the trick:
/(?| (")((?:\\"|[^"])+)\1 | (')((?:\\'|[^'])+)\1 )/xg
Demo
BTW: regex101.com is a great resource to use (which is where I got the regex above)
Update
The first one I posted works for PHP, here is one for JS
/"([^"\\]*(?:\\.[^"\\]*)*)"|\w+|'([^'\\]*(?:\\.[^'\\]*)*)'/g
Maybe I read your question incorrectly but this is working for me
/\".+\"/gm
https://regex101.com/r/wF0yN4/1

Regex for finding a specific pattern in a string

I want to write a regex to test if a string contains ]][[. For ex:[[t]][[t]].
I am able to find a string which ends with ]] using the pattern:
RegExp(/]]/)
But if i try to use the pattern:
RegExp(/]\]\(?=\[\[)/)
for testing [[t]][[t]], the console displays the following error:
Uncaught Syntax Error: Invalid regular expression: /]\]\(?=\[\[)/: Unmatched ')'
Why you have a syntax error:
You are escaping ( with \(, so you get the Unmatched ')' error in \(?=\[\[).
How to fix it:
The best way to do this depends on exactly what you want.
If you just want to check that the string contains ]][[, don't use a regex:
if (yourString.indexOf(']][[') !== -1) {
// do something
}
If you really want to use a regex, you need to escape [s but not ]s:
if (/]]\[\[/.test(yourString)) {
// do something
}
If you really want to use a regex and not capture the [[:
if (/]](?=\[\[)/.test(yourString)) {
// do something
}
If you want to check for matching [[ and ]] (like [[t]]):
if (/\[\[[^[\]]*]]/.test(yourString)) {
// do something
}
If you want to check for two [[..]] strings back-to-back:
if (/(\[\[[^[\]]*]]){2}/.test(yourString)) {
// do something
}
If you want to check for one [[..]] string, followed by exactly the same string ([[t]][[t]] but not [[foo]][[bar]]):
if (/(\[\[[^[\]]*]])\1/.test(yourString)) {
// do something
}
Here's a demo of all of the above, along with a bunch of unit tests to demonstrate how each of these works.
Use this:
if (/]]\[\[/.test(yourString)) {
// It matches!
} else {
// Nah, no match...
}
Note that we need to escape the two opening braces with \[, but the closing braces ] do not need escaping as there is no potential confusion with a character class.
You need to escape the opening square brackets because it has a special meaning in regex which represents the start of a character class.
]](?=\[\[)
Try this one, this regex must match everything you need:
(\w*[\[\]]+\w*)+
But if for every open bracket [ there must be a closed bracket ], that's different.
What exactly you want?

Replace .split() with .match() using regex in javascript

I'm having difficulties with constructing some regular expressions using Javascript.
What I need:
I have a string like: Woman|{Man|Boy} or {Girl|Woman}|Man or Woman|Man etc.
I need to split this string by '|' separator, but I don't want it to be split inside curly brackets.
Examples of strings and desired results:
// Expample 1
string: 'Woman|{Man|Boy}'
result: [0] = 'Woman', [1] = '{Man|Boy}'
// Example 2
string '{Woman|Girl}|{Man|Boy}'
result: [0] = '{Woman|Girl}', [1] = '{Man|Boy}'
I can't change "|" symbol to another inside the brackets because the given strings are the result of a recursive function. For example, the original string could be
'Nature|Computers|{{Girls|Women}|{Boys|Men}}'
try this:
var reg=/\|(?![^{}]+})/g;
Example results:
var a = 'Woman|{Man|Boy}';
var b = '{Woman|Girl}|{Man|Boy}';
a.split(reg)
["Woman", "{Man|Boy}"]
b.split(reg)
["{Woman|Girl}", "{Man|Boy}"]
for your another question:
"Now I have another, but a bit similar problem. I need to parse all containers from the string. Syntax of the each container is {sometrash}. The problem is that container can contain another containers, but I need to parse only "the most relative" container. mystring.match(/\{+.+?\}+/gi); which I use doesn't work correctly. Could you correct this regex, please? "
you can use this regex:
var reg=/\{[^{}]+\}/g;
Example results:
var a = 'Nature|Computers|{{Girls|Women}|{Boys|Men}}';
a.match(reg)
["{Girls|Women}", "{Boys|Men}"]
You can use
.match(/[^|]+|\{[^}]*\}/g)
to match those. However, if you have a nesting of arbitrary depth then you'll need to use a parser, [javascript] regex won't be capable of doing that.
Test this:
([a-zA-Z0-9]*\|[a-zA-Z0-9]*)|{[a-zA-Z0-9]*\|[a-zA-Z0-9]*}

Categories

Resources