get data from javascript array using regex - javascript

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

Related

Convert char to String in Javascript

Read it, Before it gets marked as duplicate
Sorry! I couldn't come up with a better description of the question
Anyways, I was making a simple program which reverses the given word (e.g 'word' to 'drow'). I was trying to convert the String into char array first and then printing each character backwards in the console using for loop. However, I need to save the value in a String now that I can't seem to figure out.
This is the code here:
var answer = document.getElementById("ta").value;
var arr = answer.split("");
for(i=arr.length-1;i>=0;i--) { //minus 1 because index starts at 0
str = arr[i];
console.log(str); //it works but displays each character individually
}
I just want all the characters in a String. Please help! Brevity in the answer would be appreciated
JavaScript unlike other oops, provide an inherited reverse function that reverses array. So one answer to this whould be:
let arr = answer.split("") //note this creates an array with each char as element of array
arr = arr.reverse(); //this reverses the array
let string = arr.join(""); //this joins the array into a single string
Another method would be the one you are trying to do, create your own reverse function. You are doing it all right but just missing a step, that is to join the array, you are simply printing each letter of the array and thats the property of console.log that each console.log prints to a new line. That explains why you are getting it all in new line.
var answer = document.getElementById("ta").value;
var arr = answer.split("");
var str ="";
for(i=arr.length-1;i>=0;i--) { //minus 1 because index starts at 0
str =str + arr[i];
}
console.log(str); //it should be outside the loop and print string once it has been formed
P.S:I have given as much detail I can on this to get you started but this is a very basic question and doesnt deserve to be here, you should follow some basic concepts of js on mdn or w3schools. Plus google your problems before turning to stackoverflow.
If you want to put all the characters in str you can try this way:
str= str+arr[i]
or try this way:
var str = "";
arr.forEach(element => {str= str+element});
console.log(str)

How to use array.splice() after .join()?

I'm having trouble figuring out how to remove items from an array after using the join() function.
As you'll see, the first array.splice() works, but the second does not...
var recordsArray1 = ['a','b','c','d','e','f'];
console.log(recordsArray1.length);
recordsArray1.splice('a', 1);
console.log(recordsArray1);
var recordsArray2 = ['g','h','i','j','k','l'].join('\n');
console.log(recordsArray2.length);
recordsArray2.splice('g', 1);
console.log(recordsArray2);
Thanks for any help.
Tim
Array.prototype.join(separator) converts an array into a string seperated by separator. If you want to join the elements with a newline, perform the join after any other array operations, like slicing.
https://www.w3schools.com/jsref/jsref_join.asp
join turns it from an array into a string
If I understood your need correctly, you may want to map over the elements and add newline to each, instead of joining the array to a string. This should do:
recordsArray2 = ['g','h','i','j','k','l']
recordsArray2.map((x) => x + "\n")
First, your usage of splice is not right. Your intention seems to be "please, remove exactly one a" respectively "please remove a g". But that's not how splice works. The first parameter is the index to start at, the correct usage would be .splice(0, 1) (read: remove one element starting from index 0).
Second, join converts the Array to a string using the provided sequence. So, ['g','h','i','j','k','l'].join('\n'); yields g\nh\ni\n... as a string, which does not have a join method. So, to remove the g, I suggest to join the array after you removed the g: var arr =['g','h','i','j','k','l']; arr.splice(0, 1); arr = arr.join('\n'); (or do not join it after all, since I think it was not what you intended to do). Another way would to remove the G after joining, e.g. var arr =['g','h','i','j','k','l'].join('\n').substr(2) (which would return the string starting at the third character, so the g and the following \n are removed).

How to extract inner text within nested parenthesis in a repeating manner using REGEX - Javascript?

I have blown my brains out trying to figure out the solution to this issue.
I have to extract text between the nested parenthesis. The brackets can be nested or may be more than one inside. And the crazy part is that i want this to be done using REGEX in Javascript! Insane! I know!
Example:
(This (is
(a)
(brain) killer) Aaah) (I (am) pissed) (REGEX kills)
Output: ThisisabrainkillerAaahIampissedREGEXkills
I tried this:
(((?:<\w+>)*([\w\s]*)(?:<\/\w+>)*)\*)
to extract the words. But no luck!
Note: I just want them to be extracted into groups so that I can join them later on.
You could split using this regex:
var str = "(This (is (a) (brain) killer) Aaah) (I (am) pissed) (REGEX kills)";
var result = str.split(/\s*[()]\s*/);
// remove empty strings
result = result.filter(function(s) { return s.length; });
document.write(JSON.stringify(result));
You don't need too much hassle with JS. Just use this one with a String.prototype.match(/[^\(\)\s]+?(?=[\(\)\s])/g) and you should be all fine.
[^\(\)\s]+?(?=[\(\)\s])
Debuggex Demo
Regex101 Demo

Javascript String Split

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.

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 + ","
...

Categories

Resources