extract sections of string with JavaScript - 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("-")

Related

Can i call some helper function with string name in javascript

I'm struck with some problem.
Here is what i'm trying:
can i achieve this:
var case = 'toUpperCase()';
'abcd'.case; //output ===> ABCD
user will pass case uppercase or lowercase
function getIndex(obj){
var index = window[String('someGlobalArray')].indexOf(String(obj.name).case);}
var pass = {name:'helper',case:'toUpperCase'};
someGlobalArray = ['HELPER','A','b','C',.......];
getIndex(pass);
This is possible, by using square bracket notation to access the function:
const caseFunction = 'toUpperCase'
const result = 'abcd'[caseFunction]()
console.log(result)
You've edited the question since I answered, I'll see if I can make sense of what you're asking

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

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

Capturing variable names from a select

In the back end I have written some code that reads through a file and outputs to a list of JavaScript arrays for example, the page will see:
<script>
var peanuts = ["1","s","g","3","n"];
var cashewNuts = ["d","a","f","d","n"];
var PecanNuts = ["6","m","3","x","m"];
var BrazilNuts = ["j","n","7","v","s"];
var goingNuts = ["a","e","7","m","y"];
</script>
I then want to use an array based on the value of a somewhere else in that page.
So for example:
if($('select').val()===0){
alert(firstArray[1]);
}
My issue is that the variable names are decided on what is contained in the read file, I can't know this information. Is there a way to say for example
//collect the value from the select and assign it to a var
var varN = $('select').val();
//then collect another variable that has the variable name that
//equals the value of the 'varN'
I know this seems horrendous but unfortunately based on what I need to do, it is what I need to do :(
Yes. If for example your vars are in the global scope, you can do
var val = window[varN][0]; to get peanuts:1
If you do
var nuts = {
peanuts : ["1","s","g","3","n"],
cashewNuts : ["d","a","f","d","n"],
PecanNuts : ["6","m","3","x","m"],
BrazilNuts : ["j","n","7","v","s"],
goingNuts : ["a","e","7","m","y"]
}
then you can use
var val = nuts[varN][0];
If the variables are declared directly in <script>, you can use window[varN].

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

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