Can i call some helper function with string name in javascript - 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

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

Using string interpolation in React.js regex function

I am having some issues using string interpolation in a regex, however I have also tried to log it to the console and I can see that I am doing it incorrectly.
I am trying to loop through an array of weather types to see if my API request returned a type of weather which requires me to add a class to one of my elements in the UI.
I iniitally thought the issue was using array[x] in the regex, but I have assigned this to a variable p and am still getting the same result.
let weatherTypes = ['rain', 'clouds', 'snow', 'clear', 'thunderstorm'];
for (var x= 0; x <= weatherTypes.length; x++) {
let p = weatherTypes[x];
console.log(p)
var searchPattern = `/${p}/i`;
var result = this.state.description.match(searchPattern);
console.log(`splash--weather-${p}`);
if(result !== null) {
var element = document.getElementById("splashContact");
element.classList.add(`splash--weather-${weatherTypes[0]}` );
}
}
The logic to add the class works when I abstract it out of the for loop so I know that part is working fine.
Can somebody please point me in the right direction?
edit Have now used backticks instead of quotation marks
searchPattern is a string so you just need to use the RegExp constructor before using it.
var searchPattern = `${p}/i`;
var searchPatternRegex = RegExp(`${searchPattern}`);

Split php varibale with JS into array

I have tried everything and I can not split a PHP variable into two parts so I can insert them into two input fields. I have read numerous topics here and I don't see the problem...
This peace of code gives me a result that php variable is inserted into a wanted filed.
Lets say the PHP variable is data1-data2:
document.hiderad.selectstate.onchange = updateText;
function updateText() {
var str = document.hiderad.selectstate;
document.hiderad.opis.value = str.value;
}
Code above inserted data1-data2 into wanted HTML input.
And soon as i try to split it i get undefined warning. I have tried 7 different things to approach this problem so i want even list all the versions I tried. Can someone please help?
document.hiderad.selectstate.onchange = updateText;
function updateText() {
var str = document.hiderad.selectstate;
var array = str.toString().split('-');
a = array[0], b = array[1];
document.hiderad.opis.value = a.value;
document.hiderad.iznos.value = b.value;
}
Code above gives me b undefined if i remove last line i get a undefined.
You shouldn't be using a.value and b.value, that's for getting the value of an input field, not a string. You should use that to get the value of the selectstate input.
Also, always declare local variables unless you have a specific reason to assign global variables.
function updateText() {
var str = document.hiderad.selectstate;
var array = str.value.split('-');
var a = array[0], b = array[1];
document.hiderad.opis.value = a;
document.hiderad.iznos.value = b;
}

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

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