DrPaulVella
DrPaulVella

Reputation: 449

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?

Upvotes: 0

Views: 879

Answers (5)

Eike Pierstorff
Eike Pierstorff

Reputation: 32760

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.

Upvotes: 1

S N Sharma
S N Sharma

Reputation: 1526

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

Upvotes: 1

Flash Thunder
Flash Thunder

Reputation: 12036

Not sure what You are wanting to do, but it's easier and better to:

  1. Store all the values in one array, not separate vars.
  2. Use split instead of complicated function to extract them.

var str = 'APPLE-CARROT-PAPER-HILL';
console.log(str.split('-'));

Upvotes: 1

Viktor M
Viktor M

Reputation: 301

I hope this code helping you

var name = "APPLE-CARROT-PAPER-HILL"

name.split("-")

Upvotes: 0

user10046747
user10046747

Reputation:

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

Upvotes: 0

Related Questions