This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 8 years ago.
I have a string of the form
p1=v11&p1=v12&p2=v21&p2=v22&p2=v23&p3=v31 and so on
I want to get an array of all values for p2 in javascript, e.g. in this example it would be ["v21", "v22", "v23"].
How do I do it? Do I need to use regex?
You might want to have a look at a JavaScript function I wrote to mimic the $_GET function in PHP:
http://www.martinandersson.com/matooltip/js/ma_GET.js
Google the source code for this line:
returnMe[key] = $.parseJSON( decodeURIComponent(tmpArray[1]) );
The problem with my current implementation is that any old key already stored, will have his value overwritten. What you need to do is to check if the key is already present, if so, read the old value and store him back in an array before you push the new value onto the same array.
The particular line i quoted uses JQuery to make the value into a JavaScript object. If you don't want to use JQuery for this feature then you could use JSON.parse or some other third party library.
Hope it helps, write me a comment if you don't succeed and I'll get back to you.
Try this:
var string = 'p1=v11&p1=v12&p2=v21&p2=v22&p2=v23&p3=v31';
var rawParams = string.split('&');
var params = [];
var param = '';
for (var i in rawParams) {
param = rawParams[i].split('=');
if ('p2' == param[0]) {
params.push(param[1]);
}
}
I don't recommend RegExp here, since the problem is pretty easy to be resolved with one simple for loop.
EDIT:
For sake of any haters - here's the working example: http://jsfiddle.net/j7sY6/1/
For a regex solution:
var matchs = [];
var re = /p2=([^&]+)/g;
while (match = re.exec('p1=v11&p1=v12&p2=v21&p2=v22&p2=v23&p3=v31')) {
matchs.push(match[1]);
}
Output:
matches = ["v21", "v22", "v23"]
Related
I am trying to create a custom javascript variable in GTM that returns part of a javascript variable that already exists.
Variable that already exists: window.ShopifyAnalytics.meta.product.variants.0.name
returns this: "Bamboo Basic String - Schwarz - S"
However I want to code a custom javascript variable to just return the Schwarz part, is this possible? If so what is the code that I would need?
Please can someone let me know what code to put into GTM to create this variable?
TIA
If all names are pretty much the same you could use split to get that part of string and then remove whitespaces. It would look like this:
window.ShopifyAnalytics.meta.product.variants.0.name.split('-')[1].replace(/
/g,'');
If the already existing variable is always structured the same way you could do something like this:
let variable = window.ShopifyAnalytics.meta.product.variants.0.name.split('-')
Then by calling varaible[1] you get the 'Schwartz' part of the variable.
If you want a return value you can use a function like the following and call it wherever you want.
Simply make sure to pass the correct argument content
// Declaring a function getColor that returns the second element in the list,
// trimmed (without spaces before and after)
const getColor = (content) => {
return content.split('-')[1].trim();
}
const test = "Bamboo Basic String - Schwarz - S";
console.log(getColor(test));
//console.log(getColor(window.ShopifyAnalytics.meta.product.variants.0.name));
You could split the string on the hypens (-) like this:
const productName = window.ShopifyAnalytics.meta.product.variants.0.name;
const part = productName.split(' - ')[1];
Assuming you have a consistent format, and you always want the second part after that hyphen.
split will separate parts of a string into an array where it finds a match for the argument. The first index [0] will be the product name, the second [1] will be the part you're looking for.
This could cause issues if you have a product name with a - in it too though so use with care!
If it needs to be an anonymous function for GTM, you could try the following (though I'm not a GTM expert):
function () {
const productName = window.ShopifyAnalytics.meta.product.variants.0.name;
return productName.split(' - ')[1] || 'Unknown';
}
I have looked at many of the posts involving this kind of question but I have not been able to find anything that works in this situation.
I have a variable x, it is an integer given the following value.
let x = Math.ceil(Math.sqrt(characterNumber));
My goal is to segment a string into array elements of the desired length. Using integers I can do so like the following.
let secondMessage = newMessage.match(/.{1,3}/g);
My ideal solution would be for the following to work, however whatever I am trying returns as null. In my code editor, when I pass anything that is not an integer (x in this case) the colour of the inside {} changes.
let secondMessage = newMessage.match(/.{1,x}/g);
I have tried creating a RegExp, however that also returns null.
Thank you for any answers and sorry for the long (possibly repeated) question.
Variables aren't expanded inside regular expressions. You need to construct the regular expression dynamically by creating a string and then calling new RegExp().
let x = 3;
let rx = new RegExp(`.{1,${x}}`, 'g');
let newMessage = 'abcdefghij';
let secondMessage = newMessage.match(rx);
console.log(secondMessage);
Jquery Each Json Values Issue
This question is similar to above, but not the same before it gets marked duplicated.
After realasing how to use computed values i came across another issue.
In my javascript i have the following code:
var incidentWizard = ['page1.html','page2.html','page3.html'];
var magicWizard = ['page1.html','page2.html','page3.html'];
var loadedURL = 'page1.html';
The input to this function would be (true,'incident')
function(next,wizardname)
{
var WizSize = incidentWizard.length;
wizardName = [wizardName] + 'Wizard';
var wizardPOS = jQuery.inArray(loadedURL,incidentWizard);
And now i want to use the wizardname parameter to decide what array i am going to use...
Loader(incidentWizard[wizardPOS],true);
Ive also tried
Loader([incidentWizard][wizardPOS],true);
and
Loader([incidentWizard][wizardPOS],true);
Also the loader function just required the string value in the array at wizardPOS sorry for confusion
But when trying this i always end up with the outcome...
/incidentWizard
I know this is something to do with using computed values but i've tried reading about them and cant seem to solve this issue.
Basicly i want to use the computed value of wizardName to access an an array of that name.
Please help supports, looking forward to seeing many ways to do this!
On this line:
wizardName = [wizardName] + 'Wizard';
You are attempting to concatenate the string 'Wizard' to an Array with one string element "incident". I'm assuming you just want regular string concatenation:
wizardName = wizardName + 'Wizard';
However, now you only have a string, not an array instance. To fix that, change the way you define your *Wizard arrays to something like:
var wizardyThings = {
incidentWizard : ['page1.html','page2.html','page3.html'],
magicWizard: ['page1.html','page2.html','page3.html']
};
Then your function (which is missing a name as it stands), becomes:
function someMethod(next, wizardname) {
wizardName = wizardName + 'Wizard';
var wizSize = wizardyThings[wizardName].length;
var wizardPOS = jQuery.inArray(loadedURL, wizardyThings[wizardName]);
...
}
You can only access properties of objects that way. For global values, window[ name ] will work. For simple local variables it's just not possible at all. That is, if inside a function you've got
var something;
then there's no way to get at that variable if all you have is the string "something".
I would just put each array as a prop on an object:
var obj {
incidentWizard: ['page1.html','page2.html','page3.html'],
magicWizard: ['page1.html','page2.html','page3.html']
};
Then you can just do obj['incidentWizard'] or obj.incidentWizard this will return:
['page1.html','page2.html','page3.html']
I'm trying to write a Javascript function to get the query string of the browser and allow a new key/value to be passed to the function. If the key exists, I need to replace the value. Since I've spent the last 3.5 hours on this, I haven't yet gotten around to the replacing part.
So far, I'm using the answer here: How to get the query string by javascript? to get the query string. However, it doesn't appear to work... The URL I was testing with was: http://www.site.com/poo?drwho=tombaker&companion=k9
var assoc = {};
var decode = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); };
var queryString = location.search.substring(1);
var keyValues = queryString.split('&');
for(var i in keyValues) {
var key = keyValues[i].split('=');
assoc[decode(key[0])] = decode(key[1]);
}
if(assoc["dr"] === undefined ) {
// not found. todo: replace
}
I'd really appricate any help! Is there any simpler way of doing this using JQuery?
Copy and pasted your code here: http://jsfiddle.net/6KcWh/5/, and added a call to JSON.stringify() to examine the contents of assoc. It turns out assoc is not undefined. But, of course assoc.dr is undefined, because there is no querystring argument of dr. There is a querystring argument of drwho. It looks like you were looking for the wrong querystring argument.
You appear to be misusing for...in.
Try converting your for loop to a standard for (i = 0 ; i < keyValues.length; i++) and check out some other answers about what for...in is used for in JavaScript.
This question already has answers here:
Last segment of URL with JavaScript
(30 answers)
Closed 12 months ago.
I am trying to grab the last part of the current url:
URL: http://example.com/test/action
I am trying to grab "action".
The URL is always consistent in that structure. But it may have some extra params at the end.
This is in a rails app using the prototype framework. In rails it would be params[:id].
You could simply use .split() on window.location.href, and grab the last entry.
Example:
var lastPart = window.location.href.split("/").pop();
The other answers are fine, however if your url looks like:
http://example.com/test/action?foo=bar
they will fail to give you just "action". To do this you'd use pathname, which contains only the path information exclusive of query string parameters (ie /test/action in this case):
location.pathname.split('/').pop();
use document.location.href.substring( document.location.href.lastIndexOf( '/' ) );
with jquery :
var idFromUrl = window.location.href.split("/").pop();
$('#various3').attr('href', $('#various3').attr('href').replace('placed_id', idFromUrl));
Below is my working javascript solution.Hope it helps some one and hence posting.This solution is to retrieve last part of url leaving the generally not needed query string part.It helps to identify from which page the visit happened and write logic based on that.
var url = document.referrer;
var start = url.lastIndexOf("/") + 1;
var len = url.indexOf("?");
if (len > 0)
url = url.substring(start, len);
else
url = url.substring(start);