First of all - this question has no answers at
Include variable in URL
or How can I do string interpolation in JavaScript?
I tested many variants from elsewhere before my question here.
For example, as advised at Include variable in URL
window.open('http://example.com/?q="+ myname"');
does not work with the script below.
A kind of specific wrapping is needed.
So, simplest script
<script type="text/javascript">
function sendquery() {
var myname = "John";
alert(myname);
window.open('http://example.com/?q=(myname)');
}
</script>
<button onclick="sendquery()">Query</button>
Alert perfectly shows variable John. But query sends not variable John but (myname).
Or + myname - if follow other answers.
How to wrap variable to URL query ?
It looks like you're just putting the variable in the string incorrectly. Check out template literals if you don't need to support IE.
var myname = "John";
// won't work
window.open('http://example.com/?q="+ myname"');
// will produce 'http://example.com/?q=John'
window.open(`http://example.com/?q=${myname}`);
and likewise
// won't work
window.open('http://example.com/?q=(myname)');
// valid
window.open(`http://example.com/?q=${myname}`);
If you do need to support IE then window.open('http://example.com/?q=' + myname); should work
Your string concatenation is not correct
var myname = "test"
window.open("http://example.com/?q=" + myname); // Classic string concatenation
window.open(`http://example.com/?q=${myname}`); // Using template literal
You have to wrap the URL in Template Literals
window.open(`http://example.com/?q=${myname}`);
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';
}
Sorry if this question has already been asked. If so, could someone please direct me to the thread(s)? I have not found any existing ones so far.
But my question revolves around this type of action:
var Product_Linky = document.getElementById("Product_Link_Container");
Product_Linky.style.position.left= 12px;
A literal is being applied to the attribute with the indicated units. But...can a variable be applied and if so, how would the units be specified?
The following code is not written properly, but it shows an example of the problem I have:
var Product_Linky = document.getElementById("Product_Link_Container");
Product_Linky.style.position.left= 'MyVariable_x'px ;
If a variable can be used, what is the correct syntax to include the units?
Best regards!
There's a similar question already, but to answer your question this will work:
var variable_Length = 5;
var Product_Linky = document.getElementById("Product_Link_Container");
Product_Linky.style.position.left= variable_Length + 'px' ;
Try using template Literals!
In JavaScript, if you want to make a variable "fit in" to a string, you an use the following syntax:
var num = 12;
var myString = `My number is ${num}.`;
console.log(myString);
will log
My number is 12.
One important note on this: you cannot use regular quotation marks to enclose the string. You must use the backtick:
`
(it should be right above your tab key). Otherwise, this will not work.
For more information, check out the MDN Web Docs!
For an example, check out this Codepen I made! (Try changing the myHeight variable's value.)
I hope that helps!
Do this, my friend. It's called ES6 template literal
Product_Linky.style.position.left= `${MyVariable_x}px` ;
Or you do the String concatenation like this
Product_Linky.style.position.left= MyVariable_x + 'px' ;
I have a (simple, I guess) problem with quotes, single quotes, double quotes.
I have a JS that sends data to a php file, which responds sending some data back with json. In the code below, row.Dispon is part of the response (and is working OK). But I want to "echo" row.Element inside getElementById with no success. I've tried "+row.Element+", or "'+row.Element+'". What I'm doing wrong?
if (row.Dispon=="ImageReload") {
var text='Image changed';
document.getElementById(+row.Element+).value="due";
}
Considering your code snippet only, this should do the job for that specific problem:
if (row.Dispon == "ImageReload") {
var text = 'Image changed';
document.getElementById(row.Element).value = "due";
}
You would need quotes (or double quotes) and + operators if you were trying to build a string. See this example:
var id = 42;
document.getElementById('myId' + id).value = 'something';
Assuming that row.Element contains a string already, you can directly pass it to getElementById().
Some advice here:
Read more about functions on MDN
Read more about Document.getElementById on MDN
Consider using Document.querySelector
What I'm trying to do is fetch a single piece of a string without using the hashtag element in the url. I already have a functioning code but it needs altering. So, how do I fetch any part of the url after ?.
Say I have ?fx=shipment+toys/fish-fix-fx/ as my url string; I want the button to show if shipment or fish or fx was my choice of selections for example.
Buttons showing with hastag: http://jsfiddle.net/66kCf/2/show/#iphone
Original JSFiddle (buttons not showing): http://jsfiddle.net/66kCf/2/
I want the iPhone buttons to show if fix was my choice: http://jsfiddle.net/66kCf/2/show/?fx=shipment+toys/fish-fix-fx/
try doing it with .split() and.match() like this...
var keys = window.location.href.split('?');
if (keys[1].match(/(fix|fish|fx)/))
{
$("#linkdiv").append(nextLink);
$("#linkdiv1").append(nextLink);
$("#linkdiv2").append(nextLink);
}
demo button showing : http://jsfiddle.net/LbKmf/show/?fx=shipment+toys/fish-fix-fx/
demo button not showing: http://jsfiddle.net/LbKmf/show/?reigel
Is this what your looking for:
"?fx=shipment+toys/fish-fix-fx/".split(/[\?=+\/-]/g);
window.location.search and split into array for comparisons
explained in How can I get a specific parameter from location.search?
http://css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/
Generally, Javascript doesn't have a built-in functionality for query string parameters. You can use string manipulation on window.location.search to get your parameters out of the URL string. Note that location.search includes the ? character too.
Something like this should do:
var queryString = function () {
// Anonymous function - executed immediately
// get rid of the '?' char
var str = "?fx=shipment+toys/fish-fix-fx/";
var query = str.substring(str.lastIndexOf('=')+1,str.indexOf('/'));
var vars = query.split("+");
for (var i=0;i<vars.length;i++){
console.log(vars[i]);
}
return vars;
} ();
I have a JS function which is generated by some PHP, the function call is below:
onClick=openPopup('".$row['imgname']."','".$row['adtitle']."','".$row['adviews']."')
Now this works unless the value of $row['adtitle'] contains a JS keyword. The one that brought the bug in my code to my attention was the word 'THIS'. Would there be a way to escape these values, I can't figure it out as I have already used a lot of encapsulation in this call.
Thanks in advance.
EDIT:
openPopup('efc86f7223790e91f423ef1b73278435.jpg','THIS IS A TEST ADVERT 12345678','2')
This call does not work.
openPopup('eada91a6c1197d2f2320e59f45d8ca6b.jpg','is a test','2')
however this one does work..
only thing I could figure was the THIS as when looking at the source, the text following THIS is highlighed differently.
Edit 2 : Here is my function:
function openPopup(imgname,adtitle,adviews) {
document.getElementById('popup').style.display = 'block';
document.getElementById('delimg').src = 'imgstore/' + imgname;
document.getElementById('delAdTitle').innerHTML = adtitle;
document.getElementById('delAdViews').innerHTML = adviews;
document.getElementById('confirm').onclick = function() {
location.href = '?delete=1&id=' + imgname;
}
}
Maybe it’s just a question of proper formatting:
$onclick = 'openPopup('.json_encode($row['imgname']).','.json_encode($row['adtitle']).','.json_encode($row['adviews']).')';
echo 'onClick="'.htmlspecialchars($onclick).'"';
Note that we’re abusing json_encode here to quote the JavaScript string literals. Although we shouldn’t as strictly speaking JSON strings are not a subset of JavaScript strings.