THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.
In this post, we will discuss how to convert a string into a variable in javascript.
for example, if we have a string value ‘helloworld’, we are going to convert this sting to the variable as helloworld
let str="helloworld"
function convertToVariable(str){
// helloworld="newHelloworld"
}
Multiple ways we can convert to a variable
[eval function] (/javascript-eval-function) is a global function which is sued to execute javascript code in the form of string.
let str="helloworld";
function convertToVariable(str){
var newValue = "newhelloworld";
eval("var "+ str +" = " + "'" + newValue + "'");
console.log(helloworld);// newhelloworld
}
convertToVariable(str);
In the function, the passed argument is considered as a variable and the new value is assigned to it.
eval function
is not suggested as it has performance issues.
Declared a string object and stored the string and assign the string property variable value with a new value
var str = "helloString";
window[str] = function() {
console.log("new hello string");
}
helloString();
or here is a simple example
window["stringvalue"] = "stringdata";
console.log(stringvalue);
🧮 Tags
Recent posts
Puppeteer Login Test example How to convert Double to Integer or Integer to double in Dart| Flutter By Example Best ways to fix 504 gateway time out in nodejs Applications Fix for Error No configuration provided for scss Multiple ways to List containers in a Docker with examplesRelated posts