I want to replace my title from its default to "*number* new messages | default"
Here is the code I have, it changes from default to 1 new messages fine, but it never goes above 1.
title = $('title').text();
regexp = /^(\d+)/
if (title.match(regexp))
$('title').text().replace(regexp, (parseInt("$1")+1).toString())
else
$('title').text('1 New Messages | Default')
You should be using a function as the second argument to replace, you also need to set the new value:
var title = $('title').text();
$('title').text(title.replace(regexp, function(m) { return parseInt(m, 10) + 1) }));
And, as usual, don't forget the radix argument when you call parseInt or you will be unpleasantly surprised sooner or later.
I came across this recently and the issue is to do with calling a function within the second argument of the replace function. The $1 is only valid if called directly in a string literal, not as a string argument to a function.
Another issue is that $('title').text().replace(regexp, (parseInt("$1")+1).toString()) will return a string. You need to pass the value you want to assign the text to as a function argument of the text() function like you have done in your else block.
Try this:
title = $('title').text();
regexp = /^(\d+)/
if (numToReplace = title.match(regexp))
$(title).text(title.replace(regexp, (parseInt(numToReplace[1])+1).toString()))
else
$('title').text('1 New Messages | Default')
And a JSFiddle: http://jsfiddle.net/KFW4G/
replace returns a new string, so you have to use text again to set the text to the result.
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 one c# web application in which put one link dynamically like,
if (oObj.aData[1] == '2') {
Id = oObj.aData[7];
Name = oObj.aData[2];
alert(Name);
return ' Show ';
//this is
}
function like,
function Show(id,name)
{
alert('calling');
}
but my function not calling.
Is any syntax error or anything else which I forgetting?
Please help.
You need to pass Name in quotes(''), with in quotes to be treated as string parameter. Otherwise they will be treated as JS variable which obviously you have not defined, You must be getting error 'example string' is not defined. in browser console.
return ' Show ';
Note: If Id is a string, also pass it in quotes('')
This may be of some help.
Starting from Firefox 34 and Chrome 41 you will be able to use an ECMAScript 6 feature called Template Strings and use this syntax:
String text ${expression}
Example:
var a = 5;
var b = 10;
console.log(`Fifteen is ${a + b}.`);
// "Fifteen is 15.
source: JavaScript Variable inside string without concatenation - like PHP
eg.
I have var myid="abc xyz"
then I escape metachars using function and get var x = "#"+escapechars(myid);
which evaluate to #abc\\xyz
Now when I try to do $(x) it doesn't get any element
but when I type $("#abc\\xyz") in watch it gets the element.
I am attaching a screenshot for same scenario.
Problem is : I want to select the element using variable
Thank you.
Here is the jsfiddle for my scenario.
http://jsfiddle.net/9hq4nzvx/3/
This >http://jsfiddle.net/9hq4nzvx/5/ solves the issue.
When we are using string variable that time we only need a single backslash instead of 2.
function escapechars now returns : "#abc\ xyz" which gets the element as needed.
var selection ="abc xyz";//this can be anything else comes from an array.
var x = "#"+escapeStr(selection); //"#abc\\\\\ xyz";
$(x).html("<h1>Hii</h1>");//why don't I get element here?
console.log(x);
alert(x);
$("#abc\\ xyz").append("<h2>bye</h2>");
function escapeStr(str) {//escape special chars from selectors
if (str)
return str.replace(/([ !"#$%&'()*+,.\/:;<=>?#[\\\]^`{|}~])/g, '\\$1');
return str;
}
I know the code is very little and I'm missing something small.
fiddle : http://jsfiddle.net/0oa9006e/1/
code :
var veri = "+???+Girdiğiniz eposta adresi 'adfadf' geçersiz.-???-";
var a = veri.match(/\+[\?]*\+(.*)*\-[\?]*\-/g);
a = a.replace(/[\+\-\?]*/g , "");
alert(a);
String.match(param) method returns an Array containing all matches. and array in javascript doesn't have .replace method. hence Error. You could try out something like:
a = a.toString().replace(/[\+\-\?]*/g,""); // Array to string converstion
Your match is returning an array, which doesn't have replace. Try:
a = a[0].replace(/[\+\-\?]*/g , "");
var veri = "+???+Girdiğiniz eposta adresi 'adfadf' geçersiz.-???-";
var a = veri.match(/\+[\?]*\+(.*)*\-[\?]*\-/g);
// The variable 'a' is now an array.
// The first step in debugging is to always make sure you have the values
// you think you have.
console.log(a);
// Arrays have no replace method.
// Perhaps you are trying to access a[0]?
// or did you mean to modify `veri`?
a = a.replace(/[\+\-\?]*/g , "");
alert(a);
When veri.match(/\+[\?]*\+(.*)*\-[\?]*\-/g) is executed, your variable a is initialized to a JavaScript Array, which does not have a replace method.
Use a RegEx tool like Regex101 to see how your regular expression matches on the string veri, and then perform the replace operation on the appropriate element of that array.
Here's an example of your regular expression in use: http://regex101.com/r/hG3uI1/1
As you can see, your regular expression matches the entire string held by veri, so you want to perform the replace operation on the first (and only) element returned by match:
a = a[0].replace(/[\+\-\?]*/g , "");
When I have something like this:
var str = "0123";
var i = 0;
str.replace(/(\d)/g,function(s){i++;return s;}('$1'));
alert(i);
Why does "i" equal 1 and not 4?
Also, is it possible to pass the real value of $1 to a function (in this case 0,1,2,3) ?
When you use string.replace(rx,function) then the function is called with the following arguments:
The matched substring
Match1,2,3,4 etc (parenthesized substring matches)
The offset of the substring
The full string
You can read all about it here
In your case $1 equals Match1, so you can rewrite your code to the following and it should work as you desire:
var str = "0123";
var i = 0;
str.replace(/(\d)/g,function(s,m1){i++;return m1;});
alert(i);
The expression
function(s){i++;return s;}('$1')
Creates the function and immediately evaluates it, passing $1 as an argument. The str.replace method already receives a string as its second argument, not a function. I believe you want this:
str.replace(/(\d)/g,function(s){i++;return s;});
You are calling the function, which increments i once, and then returns the string '$1'.
To pass the value to a function, you can do:
str.replace(/\d/g, function (s) { /* do something with s */ });
However, it looks like you don't actually want to replace anything... you just want a count of the number of digits. If so, then replace is the wrong tool. Try:
i = str.match(/\d/g).length;