JS How to include a variable in a path? - javascript

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

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("-")

method plugin doesn't work within Function Constructor

What I'm trying to achieve in JavaScript is to make a method of the plugin I'm working with (called "Plugin") flexible. The plugin runs in an iFrame and has cross-domain trust settings applied. I want to use variables to build the method parameter rather than hard code it.
The hardcoded version is shown below and I've double checked this works. I've used it in functions and in a Function constructor. Both work.
window.Plugin.Session.Tags({
TagName: 'SomeTagName',
TagValueTagging: 'sometagvalue; secondtagvalue',
TagValueTaggingReset: '*'
}).Update();
My objective is to replace the 'sometagvalue' with a variable, so I can set the tag dynamically. The help says the parameter is a constant JSON string.
I've tried the following things:
build the parameter as string. Result: Though myText holds the exact same string as in the hardcoded version, the method is not executed.
var myTag = '\\'DEELNEMER ; name\\' ';
var myText = "{TagName : 'Workflow'," +
" TagValueTagging : " + myTag +
", TagValueTaggingReset : '*'}";
alert("myText = " + myText);
x = window.Plugin.Session.Tags(myText);
x.Update();
2) using new Function constructor. I created a variable with the session object and inserted that as parameter. In order to proof myself that I working with the right object, I've put it's LID in an alert as well outside as inside the constructor. Result: the Session.LID was the same inside and outside the constructor, but tagging did not happen.
var myFunction = "alert(\"in constructor Session.LID = \" + prmSession.LID); window.addTag =
prmSession.Tags({TagName : \'Workflow\', TagValueTagging : \'DEELNEMER\' , TagValueTaggingReset :
\'*\'}); window.addTag.Update();"
var addTagFunction = new Function("prmSession", myFunction)
var prmSession = window.Plugin.Session;
alert("in main function Session.LID = " + prmSession.LID);
addTagFunction(prmSession);
3) using JSON stringify. Again Result: Tag was not set, in neither variant..
var myTag = 'DEELNEMER ; name ';
var obj = new Object();
obj.TagName = "Workflow";
obj.TagValueTagging = myTag;
obj.TagValueTaggingReset = "*";<br/>
var myJSON= JSON.stringify(obj);
Plugin.Session.Tags(myJSON).Update();<br/>
/*variant 2*/<br/>
var myObjParsed = JSON.parse(myJSON);
Plugin.Session.Tags(myObjParsed).Update();
I would be very greatful for a tip how to solve this issue.
Regards
Plugin appears to translate the javascript into backend data queries during the compilation of the solution.
The use of parameters is therefore not possible.

Angularjs function meaning

I am a beginner in programming. I would like to understand what the beginning of this angular function is doing line by line ?
function UserProfileService($http, ApiConfigService) {
var profileUrl = ApiConfigService.getEndpoints().user_service +
'/v2/users/profile';
var oauthUrl = ApiConfigService.getEndpoints().oauth_service +
'/v2/oauth';
Thanks!
It is creating two different string variables. The base url comes from the ApiConfigService and rest is concatenated there to the baseurl.
We could assume the following:
ApiConfigService.getEndpoints().user_service = 'http://example.com/user-service'
ApiConfigService.getEndpoints().oauth_service = 'http://example.com/oauth-service'
then the variables here would get the following values:
profileUrl = 'http://example.com/user-service/v2/users/profile'
oauthUrl = 'http://example.com/oauth-service/v2/oauth'

Is it possible to use search.luceneSearch with previously declared vars?

I want to create a script which will be validated by an action/folder rule in Share.
I was thinking about using previously declared vars, something like these:
var clientsite = "client"
var docfolder = "document_alias"
var docyear = 2015
And my code would be something like this:
var folder = search.luceneSearch(" PATH:\"/app:company_home/st:sites/**clientsite**/**docfolder** \" AND TYPE:\"cm:folder\" AND \#cm\\:name:\"**docyear**\" ");
if (folder == null || folder.length == 0) {
//create new folder called 'docyear'
}
else {
//move to the already existing folder related to 'docyear'
}
Where the bold(I tried to bold items with * in the code, sorry) values would be the vars previously declared.
Is there a way to use vars like in that way??
Thanks!
Sure! You just need to append them, the standard javascript string creation doesn't support template parameters, so take your line
var folder = search.luceneSearch(" PATH:\"/app:company_home/st:sites/**clientsite**/**docfolder** \" AND TYPE:\"cm:folder\" AND \#cm\\:name:\"**docyear**\" ");
And make it something like
var folder = search.luceneSearch(" PATH:\"/app:company_home/st:sites/"+clientsite+"/"+docfolder+" \" AND TYPE:\"cm:folder\" AND \#cm\\:name:\""+docyear+"\" ");

remove specific text from variable - jquery

I have a variable in my script containing data test/test1. The part test/ is already stored in another variable. I want to remove test/ from the previous variable and want to store remaining part in another variable. how can I do this??
Thanks in advance...:)
blasteralfred
In your case, x/y:
var success = myString.split('/')[1]
You split the string by /, giving you ['x', 'y']. Then, you only need to target the second element (zero-indexed of course.)
Edit: For a more general case, "notWantedwanted":
var success = myString.replace(notWantedString, '');
Where notWantedString is equal to what you want to get rid of; in this particular case, "notWanted".
If your requirement is as straightforward as it sounds from your description, then this will do it:
var a = "test/test1";
var result = a.split("/")[1];
If your prefix is always the same (test/) and you want to just strip that, then:
var result = a.substring(5);
And if your prefix varies but is always terminated with a /, then:
var result = a.substring(a.indexOf("/") + 1);
To split at the first occurence of "/":
var oldstring = "test/test1";
var newstring = oldstring.substring(oldstring.indexOf("/")+1);
There are many other ways to do this, the other answers work fine too.
Have your pick:
JavaScript replace() function.
var data = "test/test1";
data = data.replace(/data/gi, 'test/');
Or:
var data = "test/test1";
var dataArray = data.split('/');
var data1 = dataArray[0];
var data2 = dataArray[1];

Categories

Resources