how do I convert to string in js - javascript

I have a variable that takes a string and uses the ToLowerCase Function and I want to be able to use the charAt function for example
if (message.content.charAt(0) === '!'){
console.log('correct')
}
although that is a string and I have a variable named Text this is the Variable
var Text
Text = message.content.toLowerCase()
although there is no error in this I want to be able to use the charAt function so I need it to be converted to a string how would I do this?

You can use the toString() method, something like this: var text = message.content.toString().toLowerCase()
Or also var text = String(message.content).toLowerCase()

Related

How do I create a custom javascript variable that selects part of an already existing javascript variable?

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';
}

Node.JS - Filename won't accept a variable

doesn't work:
console.log(obj.html_template); // outputs "myfile.html"
var html = fs.readFileSync(JSON.stringify(obj.html_template)); // file not found.
works:
console.log(obj.html_template); // "myfile.html"
var html = fs.readFileSync("myfile.html"); // Works.
I'm going crazy.
> JSON.stringify('myfile.html')
""myfile.html""
Your code is looking for the file "myfile.html" (note the superfluous quotes) in the filesystem. It doesn't exist.
Just look for it without stringification:
var html = fs.readFileSync(obj.html_template);
When you call JSON.stringify, it will convert all the Strings to the JSON format Strings, with surrounding double quotes. Quoting ECMAScript 5.1 Specification for JSON.stringify,
If Type(value) is String, then return the result of calling the abstract operation Quote with argument value.
And the Quote operation, is defined here, which basically surrounds the string with " and takes care of special characters in the String.
So JSON.stringify converts, a string, for example, abcd.txt to "abcd.txt", like this
console.log(JSON.stringify("abcd.txt"));
// "abcd.txt"
which is not equal to abcd.txt.
console.log(JSON.stringify("abcd.txt") == "abcd.txt");
// false
but equal to "abcd.txt".
console.log(JSON.stringify("abcd.txt") == '"abcd.txt"');
// true
So, your program searches for a file named "abcd.txt" instead of abcd.txt. That is why it is not able to find the file and fails.
To fix this problem, just drop the JSON.stringify and pass the string directly, like this
var html = fs.readFileSync(obj.html_template);
why are you using JSON.stringify in the first place? you should be able to just do
var html = fs.readFileSync(obj.html_template);

TypeError : undefined is not a function when calling replace method

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 , "");

How do I retrieve nodes with one or another value with XPATH

I have a javascript function that needs to retrieve certain nodes through xpath using document.evaluate, till now I am using something like
.//span[contains(#title, 'alerting')] | .//span[contains(#title, 'caution')]
But it turn in a very long string when values to match are more. I cannot use [#title = word], because I need to retrieve the elements whose atributes contains some string. I have tried things like
.//span[contains(#title, ('alerting'|'caution'))]
But it does not retrieve anything.
Can you give me an idea to shorten the first sintax?
Why not just create a function that creates the string and build the expression programmatically, and not worry about it? Roughly:
function spanContains(s) {
return ".//span[contains(#title, '" + s + "')]";
}
var contains = [spanContains('word1'), spanContains('word2')].join("|");
You could also try using matches instead of contains, although I'm not sure what the JavaScript syntax for that would be, or if it's supported.
XPath should be this way:-
.//span[contains(#title, 'alerting') or contains(#title, 'caution')]
.//span[contains(#title, ('alerting'|'caution'))]
This is invalid XPath -- the union operator | can only have arguments that are node-sets -- not strings.
Use:
.//span[#title
[contains(.,'alerting')
or
contains(.,'caution')
]
]
Instead of using document.evaluate(), you could use jquery in which case you could do:
$('span').filter(function() {
var title = $(this).attr('title');
return title != undefined && title.search(/(alerting|caution)/) != -1;
});

Javascript: how to pass found string.replace value to function?

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;

Categories

Resources