Removing [ and ] from xmlhttp array javascript variable - javascript

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]));

Related

Javascript include delimiter when using command [.split]

Question:
Is it possible to keep the selected delimiter using javascript [.split], without involving regex? In below example I am sending in the commands using node.js.
// A css text string.
var text_string = "div-1{color:red;}div-2{color:blue;}";
// Split by [}], removes the delimiter:
var partsOfStr = text_string.split('}');
// Printouts
console.log("Original: " + text_string); // Original.
console.log(partsOfStr); // Split into array.
console.log(partsOfStr[0]); // First split.
console.log(partsOfStr[1]); // Second split.
The output:
Original: div-1{color:red;}div-2{color:blue;}
[ 'div-1{color:red;', 'div-2{color:blue;', '' ]
div-1{color:red;
div-2{color:blue;
Wanted behaviour:
I need the output to include the delimitor [ } ]. The result lines should look line this:
div-1{color:red};
div-2{color:blue};
I did find below question but it does not use javascript split, it uses regex:
Javascript split include delimiters
Here's a way using replace - although technically there is a regex involved. Techical in an almost pedantic way since it matches the actual strings, only between slashes rather than quotes.
var text_string = "div-1{color:red;}div-2{color:blue;}";
var partsOfString = text_string.replace(/;}/g, "};\n")
console.log(partsOfString);

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

Problems to negate regex pattern

I have several regex patterns and i have to negate them all, so i am trying to build somo generic regex negate, something like /^(anypattern)/ but I am having troubles..
for example, I have this text: zzzzzAAAAA#AAAA_AAAzzzzzzAAAAA#AAAA.AAAggggggAAAAA#AAA.AAAooooooooo
and this pattern: [A-Z]+#[A-Z]+\\.[A-Z]{2,4}, I need something to negate this. I would get the an array with the following matches:
zzzzzAAAAA#AAAA_AAAzzzzzz , gggggg , ooooooooo
Note that AAAAA#AAAA_AAA was included only because this have a _ instead a dot
my regex are all simple, dont having any of these especial caracteres: \s,\t,\r,\n,\v,\f,\b,etc..
I tryed to solve it with negative lookarounds but without success
Try using a split with the regex exactly as you have it?
var input = "zzzzzAAAAA#AAAA_AAAzzzzzzAAAAA#AAAA.AAAggggggAAAAA#AAA.AAAooooooooo"
var output = input.split(/[A-Z]+#[A-Z]+\.[A-Z]{2,4}/)
console.log(output)
// outputs ["zzzzzAAAAA#AAAA_AAAzzzzzz", "gggggg", "ooooooooo"]
However, you may need to clean out empty elements, consider
var input = "AAAAA#AAAA.AAAzzzzzAAAAA#AAAA_AAAzzzzzzAAAAA#AAAA.AAAggggggAAAAA#AAA.AAAooooooooo"
var output = input.split(/[A-Z]+#[A-Z]+\.[A-Z]{2,4}/)
console.log(output)
// outputs ["", "zzzzzAAAAA#AAAA_AAAzzzzzz", "gggggg", "ooooooooo"]
After the setting the output variable, you can add this courtesy of this answer
output = output.filter(function(n){ return n != undefined && n.length})
// which outputs ["zzzzzAAAAA#AAAA_AAAzzzzzz", "gggggg", "ooooooooo"]

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]*}

Splitting string in javascript

How can I split the following string?
var str = "test":"abc","test1":"hello,hi","test2":"hello,hi,there";
If I use str.split(",") then I won't be able to get strings which contain commas.
Whats the best way to split the above string?
I assume it's actually:
var str = '"test":"abc","test1":"hello,hi","test2":"hello,hi,there"';
because otherwise it wouldn't even be valid JavaScript.
If I had a string like this I would parse it as an incomplete JSON which it seems to be:
var obj = JSON.parse('{'+str+'}');
and then use is as a plain object:
alert(obj.test1); // says: hello,hi
See DEMO
Update 1: Looking at other answers I wonder whether it's only me who sees it as invalid JavaScript?
Update 2: Also, is it only me who sees it as a JSON without curly braces?
Though not clear with your input. Here is what I can suggest.
str.split('","');
and then append the double quotes to each string
str.split('","'); Difficult to say given the formatting
if Zed is right though you can do this (assuming the opening and closing {)
str = eval(str);
var test = str.test; // Returns abc
var test1 = str.test1; // returns hello,hi
//etc
That's a general problem in all languages: if the items you need contain the delimiter, it gets complicated.
The simplest way would be to make sure the delimiter is unique. If you can't do that, you will probably have to iterate over the quoted Strings manually, something like this:
var arr = [];
var result = text.match(/"([^"]*"/g);
for (i in result) {
arr.push(i);
}
Iterate once over the string and replace commas(,) following a (") and followed by a (") with a (%) or something not likely to find in your little strings. Then split by (%) or whatever you chose.

Categories

Resources