Javascript String Split - javascript

I've a String like following:
var str = '35,35,105,105,130,208,50,250';
I would like to split this string and get like this:
var arr = [[35,35],[105,105],[130,208],[50,250]];
I tried some ways, but none of them give me anything. I tried with looping to find the even comma position and split, but that doesn't seem good to me. Please give me some suggestion on this. I'm looking for RegEx Solution.

One possible approach:
'35,35,105,105,130,208,50,250'.match(/\d+,\d+/g).map(function(s) {
return s.split(',');
});
Another crazy idea in one line:
JSON.parse('['+ '35,35,105,105,130,208,50,250'.replace(/\d+,\d+/g, '[$&]') +']');

Here's one way to do it.
var values = str.split(','),
output = [];
while(values.length)
output.push(values.splice(0,2));
If str contains an odd number of values, the last array in output will contain only one value using this method.

Related

Why is JavaScript's split() method not splitting on ":"?

So to start off, a bit of context. I am pulling data from the following url: "https://webster.cs.washington.edu/pokedex/pokedex.php?pokedex=all" using a GET method. The data returned is a series of Pokemon names and image names in the following format.
Name1:name1.png
Name2:name2.png
...
The list is 151 items long. When I call the typeOf() method "String" is returned, so I am fairly certain it is a String I am dealing with here. What I would like to do is split the String on the delimiters of "\n" and ":".
What I would like:
Name1,name1.png,Name2,name2.png...
After some experimentation with Regex, I found that the Regex to do this was "\n|:". Using this I wrote the following line to split the String apart. I tested this Regex on https://regex101.com and it seems to work properly there.
var splitData = data.split("\n|:");
("data" is the String I receive from the url.)
But instead of splitting the String and placing the substrings into an array it doesn't do anything. (At least as far as I can see.) As such my next idea was to try replacing the characters that were giving me trouble with another character and then splitting on that new character.
data = data.replace("\n", " ");
data = data.replace("/:/g", " ");
var splitData = data.split(" ");
The first line that replaces new line characters does work, but the second line to replace the ":" does not seem to do anything. So I end up with an array that is filled with Strings that look like this.
Name1:name1.png
I can split these strings by calling their index and then splitting the substring stored within, which only confuses me more.
data = data.replace("\n", " ");
var splitData = data.split(" ");
alert(splitData[0].split(":")[1]);
The above code returns "name1.png".
Am I missing something regarding the split() method? Is my Regex wrong? Is there a better way to achieve what I am attempting to do?
Right now you are splitting on the string literal "\n|:" but to do a regex you want data.split(/[:\n]/)
The MDN page shows two ways to build a Regex:
var regex1 = /\w+/;
var regex2 = new RegExp('\\w+');
The following test script was able to work for me. I decided to use the regex in the split instead of trying to replace tokens in the string. It seemed to do the trick for me.
let testResponse = `Abra:abra.png
Aerodactyl:aerodactyl.png`;
let dataArray = testResponse.split(/\n|:/g);
let commaSeperated = dataArray.join(',');
console.log(commaSeperated);
So you can simply use regex by excluding the quotes all together.
You can look at the documentation here for regular expressions. They give the following examples:
var re = /ab+c/;
var re = new RegExp('ab+c');
See below for your expected output:
var data = `Name1:name1.png
Name2:name2.png`;
var splitData = data.split(/[\n:]/);
console.log(splitData);
//Join them by a comma to get all results
console.log(splitData.join(','));
//For some nice key value pairs, you can reduce the array into an object:
var kvps = data.split("\n").reduce((res, line) => {
var split = line.split(':');
return {
...res,
[split[0]]: split[1]
};
}, {});
console.log(kvps);
I tried and this works good.
str.split(/[:\n]/)
Here is a plunker.
plunker

Inverse regex javascript

I'm trying to remove everything in a string that does not match 'standard' characters. Heres what I have so far:
var result = myString.replace(/^(?![A-Za-z0-9]+)/g, '');
Which does not work. Can someone point to me what I'm not doing right?
I think you mean this:
var result = myString.replace(/[^a-z0-9]/gi,'');

get data from javascript array using regex

After several frustrating hours, I turn to the stackoverflow group for some help. While I know that regex can solve my problem, I do not know enough (and am on a deadline, so can't learn what I need before the deadline) to do what I need to do.
My issue is that I have the following array:
(['ad53930','160x600','&PG=SPTRF3','&AP=1090','regular'],
['ad55852','728x90','&PG=SPTRF1','&AP=1390','regular'],
['ad52971','300x250_pginterstitial','&PG=SPTRF4','&AP=1089','pgInterstitial'],
['ad52969','300x250','&PG=SPTHP4','&AP=1089','regular'])
and need to extract the 6 digit code after the &PG=. I was able to hobble together some regex to pull the entire &PG=XXXXXX string, but built it in Chrome's console, and after the browser crashed, lost the regex. What I am trying to accomplish is to get a finished product of 'SPTRF3,SPTRF1,SPTRF4,SPTHP4' from the array above, either in another array or string.
Any help would be greatly appreciated!
Why do you need regular expressions? You can just use a substring on that string in the array: .substr(3).
If the "&PG=" string is always in the array at index 2, then you can iterate through the array of arrays like this:
for (idx in myArray)
console.log(myArray[idx][2].substr(4), ",");
Using regex capture groups, pass this regex to every item with a for loop and push results to another array products
var products = []
for (var i=0, l=arr.length, p; i<l; i++){
p = /&PG\=(.+)/.exec(arr[i])[1]
if (p) products.push(p)
}
This worked for me:
/&PG=[A-Z]{5}\d/g
it may work for you.
var arr = ['ad53930','160x600','&PG=SPTRF3','&AP=1090','regular']
var num = arr[2].substr(4); // it will give SPTRF3

how to check next existence of a character in string in javascript

Hi All I have a string like this
var data='mobile,car,soap,room';
I am parsing from this string and making this string as comma sperated and pushing it into an array like this
var availableTags=[];
var str='';
for(i=0;i<data.length;i++)
{
if(data[i]==',')
{
availableTags .push(str);
str='';
}
else
{
str +=data[i];
}
}
But I am doing wrong as I cannot get the last value after comma... Now What I want to ask how can I come to know the next existence of , in my string that whether it exists or not. So that I can also include the last value.
I would also appreciate if someone guide me that how can I accomplish that same task some other way.
I want the string to be an array and it should look like this
["mobile","car","soap","room"]
you can use
var availableTags = data.split(",");
it will handle all the things. and will result in an array.
You can use:
data.split(/,/)
See the split documentation.
After loop, you need to check value of str and add it too. It can contain the rest after last comma, or it can be empty in case comma was the last character in data.
But as other pointed, split is probably better way to do it.
As far as fixing your existing function, try adding the following after the for loop:
if (str != "")
availableTags.push(str);
(When the loop ends str holds whatever came after the last comma.)
But like the other answers said, you can just use the array .split() method:
var availableTags = data.split(",");
You could append an extra comma on at the start:
data = data + ","
...

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