Invoke method (that takes string param) on string via chaining - javascript

Can I do something like this?
var mystring = "http%3A%2F%2Fstackoverflow.com%2F";
var mydecodedstring = mystring.apply(decodeURIComponent);
I know I can do this
var mydecodedstring = decodeURIComponent(mystring);
But I'd like to chain this if possible for syntactic purposes. Just curious if it's possible. My goal is:
mystring.?????

Your should see this to see how apply works. You could do something like:
var mystring = "http%3A%2F%2Fstackoverflow.com%2F";
var mydecodedstring = decodeURIComponent.apply(null, mystring);
Clearly, apply will not provide what you are looking for.
You could define your own function on the String prototype for decoding or define it only on your object.

maybe you want to add a new method to String object?
String.prototype.apply= function(entry){
return decodeURIComponent(entry);
}
var mystring = "http%3A%2F%2Fstackoverflow.com%2F";
var mydecodedstring = mystring.apply(decodeURIComponent);

Related

extract sections of string with JavaScript

Suppose I have a string variable {{Name}} that looks like this:
APPLE-CARROT-PAPER-HILL
I want to create 4 variables using JavaScript that captures each piece:
var1 = APPLE
var2 = CARROT
var3 = PAPER
var4 = HILL
In Tag Manager, I assume the JS for var1 would be:
function(){
var name = {{Name}}.slice(0, {{Name}}.indexOf("-"));
return name;
}
but how then to do the others?
Not sure what You are wanting to do, but it's easier and better to:
Store all the values in one array, not separate vars.
Use split instead of complicated function to extract them.
var str = 'APPLE-CARROT-PAPER-HILL';
console.log(str.split('-'));
var name_str = "APPLE-CARROT-PAPER-HILL";
function a(){
var v1, v2, v3, v4;
var name = name_str.split('-');
[v1, v2, v3, v4] = name;
console.log(v1);
console.log(v2);
console.log(v3);
console.log(v4);
}
a();
Since you are using GTM (so far the other answers have ignored the google-tag-manager tag), I suspect your actual question is if there is a way to solve this with a single variable. Alas, no, you need to create a variable for each piece of your string
APPLE-CARROT-PAPER-HILL
// Apple
function(){
return {{Name}}.split("-")[0];
}
// Carrot
function(){
return {{Name}}.split("-")[1];
}
etc.
You can make this a bit nicer but creating a custom template that returns the value for a given index from an array, but if you want to use the parts of the name in separate fields (e.g. for use as custom dimensions) then alas you need a variable for each segment of your delimited string.
Try This,
let name = 'APPLE-CARROT-PAPER-HILL';
let nameAr = name.split('-');
let var1 = nameAr[0];
let var2 = nameAr[1];
let var3 = nameAr[2];
let var4 = nameAr[3];
I hope this code helping you
var name = "APPLE-CARROT-PAPER-HILL"
name.split("-")

Referencing, then calling, a prototype function

I am trying to make an array of functions so that I can train a machine learning algorithm. One problem I am running into, for instance:
var fun = [String.prototype.split];
var str = 'test1&test2';
var result = str.fun[0]('&');
gives me the error of "cannot read property 0 of undefined". this is because the str does not have the literal fun array within itself to be called. Is the only way to correct this is to wrap every function such as the following or is there another way:
function splitter (str1, str2) {
return str1.split(str2);
}
var fun = [splitter];
var str = 'test&test';
var result = fun[0](str, '&');
If there is another way to do this I would really like to know as it will save me a lot of time wrapping every function like the above.
var arr = [String.prototype.split];
var str = 'test&test';
arr[0].call(str, '&');
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call

JS How to include a variable in a path?

The following variable contains a string that is a path to an image.
iconBlue.image = 'http://www.site.com/icon1.jpg';
How can include a variable in this path? Let me explain more detailed. Lets say there are many icons in a folder icon1.jpg icon2.jpg etc. I have a variable named iconspec that depending on its value (1 or 2 or 3 etc) points to the icon I must use.
How can i include variable iconspec in the path?
iconBlue.image='http://www.site.com/icon"iconspec".jpg
Something like this i guess but with correct syntax.
You just need to put it like a simple string with variable.
In your case, you should do this:
iconBlue.image = 'http://www.site.com/icon'+iconspec+'.jpg';
The + operator is like the . in PHP, it merge string.
iconBlue.image='http://www.site.com/icon'+iconspec+'.jpg';
To take a little different route, you could encapsulate the concatenation in a function and make it a bit more reusable:
var icon = function(){
this.path = '';
this.imageName = '';
this.imagePath = function() { return this.path + '/' + this.imageName };
};
var iconBlue = new icon(),
iconRed = new icon();
iconBlue.path = "c:\\stuff";
iconBlue.imageName = "icon1.jpg";
iconRed.path="c:\\morestuff";
iconRed.imageName = "icon2.jpg";
alert(iconBlue.imagePath());
alert(iconRed.imagePath());
The simplest solution is to use the + to concatenate the variable to the string:
var name = 'sachleen';
var result = 'my name is ' + name;
Output: my name is sachleen
There are a couple of more powerful options available as well.
JavaScript sprintf() is a sprintf implementation for JS.
string.format in JS

Javascript Newb : How do I instantiate a var as "blah.1" and "blah.2"?

I currently have a block like this defining some vars
var slider_1 = document.querySelector('#slider_1');
var slider_2 = document.querySelector('#slider_2');
...
And func's that take ID's like this:
function updateFromInput(id){
if(id==1){
var x = input_1.value*1;
x = Math.round((x*ratio)-offset);
slider_1.x.baseVal.value = x/scale;
}else if(id==2){
var x = input_2.value*1;
x = Math.round((x*ratio)-offset);
slider_2.x.baseVal.value = x/scale;
}
};
I am trying to refactor a bit.
I'm thinking that if I could, instead, instantiate my vars with dots rather than underscores like
var slider.1 = document.querySelector('#slider_1');
var slider.2 = document.querySelector('#slider_2');
then I'd be able to better utilize the ID already getting passed into my func's and eliminate tons of duplication.
I was hoping to simplify my funcs with something like a single call for slider.id.x.baseVal.value = x/scale; rather than having to have that code in each of the IF/ELSE conditions.
When I try that though, I get an error saying " Uncaught SyntaxError: Unexpected number ".
How should this be done?
You can't use a plain numeric key in an object.
You can do this, though:
var slider = {}; // or = [], if array syntax is more appropriate
slider[1] = ...
slider[2] = ...
Furthermore, the syntax you suggested isn't allowed if the key is actually a variable rather than a literal token.
In your example slider.id actually refers to the object with literal key id, not whatever value the variable id happens to have.
You have to put the variable inside square brackets, i.e. slider[id], so your function would be written thus:
function updateFromInput(id){
var x = +input[id].value;
x = Math.round((x*ratio)-offset);
slider[id].x.baseVal.value = x/scale;
};
You can't. The . is an invalid character for a variable identifier.
You can use it in object properties though.
var sliders = {
"slider.1": document.querySelector('#slider_1'),
"slider.2": document.querySelector('#slider_2')
};
Then use the square bracket version of the member operator to access the property.
alert( sliders["slider.1"].id );

javascript how to add a variable to a string

I'm using javascript and jquery, I have a string like
var apiUrlAnswer = 'https://api.stackexchange.com/2.0/answers/{ids}?order=desc&sort=activity&site=stackoverflow';
I need replace the {ids} with a variable.
In C# is possible to use a method called
String.Format(https://api.stackexchange.com/2.0/answers/{0}?order=desc&sort=activity&site=stackoverflow, myVariable);
I would like to know if exist something similar in Javascript so I can avoid simple string concatenation.
Thanks for your help!
Use the String .replace() method:
var apiUrlAnswer = 'https://api.stackexchange.com/2.0/answers/{ids}?order=desc&sort=activity&site=stackoverflow';
apiUrlAnswer = apiUrlAnswer.replace("{ids}", yourVariable);
// OR, if there might be more than one instance of '{ids}' use a regex:
apiUrlAnswer = apiUrlAnswer.replace(/\{ids\}/g, yourVariable);
Well here's a String.format (like c#); I've extended javascripts String object to include a format method like this:
String.format = function(stringToFormat, argsForFormat) {
for (var i = 0; i < argsForFormat.length; i++) {
var regex = new RegExp('\{(' + i + ')}', 'g');
stringToFormat = stringToFormat.replace(regex, argsForFormat[i]);
}
return stringToFormat;
};
You can call it like this
var args = [1, 'activity', 'stackoverflow', 'desc']
var apiUrlAnswer = 'https://api.stackexchange.com/2.0/answers/{0}?order={3}&sort={1}&site={2}';
var apiUrlAnswer = String.format(apiUrlAnswer, args);
Or an inline version would look like this
var apiUrlAnswer = String.format('https://api.stackexchange.com/2.0/answers/{0}?order={3}&sort={1}&site={2}', [1, 'activity', 'stackoverflow', 'desc']);
and another example
String.format("http://{0}.{1}.com", ['www', 'stackoverflow']);
If you are doing this frequently, a more robust alternative to using a regex is to use a client side templating engine like mustache.js. I have used this successfully and it's quick and lightweight.
var view = {
ids: "Andrew"
};
var output = Mustache.render("https://api.stackexchange.com/2.0/answers/{{ids}}?order=desc&sort=activity&site=stackoverflow", view);
This has the advantage of separating your data and presentation nicely.
How about just using replace:
apiUrlAnswer = apiUrlAnswer.replace('{ids}', 'test');
Try
var id = 'your_id';
var apiUrlAnswer = 'https://api.stackexchange.com/2.0/answers/'+id+'?order=desc&sort=activity&site=stackoverflow';

Categories

Resources