How to retrieve string stored inside a variable? - javascript

I have a variable params inside a function someFunction(),
function someFunction() {
var params = ""
params += "type=" + type + "&intro=" + intro + "&val=" + val; // then I add a value on params
console.log(params.val); // now, how can i do this?
}
Any ideas?

Better to write your custom function.
Here what I have tried.
window.onload = function() {
var params = "";
var type = "types";
var intro = "int";
var val = "values";
params += "type=" + type + "&intro=" + intro + "&val=" + val;
var convertToObject = function(strParams) {
var objQueryString = {};
var arrParam = strParams.split('&');
console.log(arrParam)
arrParam.forEach(function(value, key) {
var arrKyValue = value.split('=');
objQueryString[arrKyValue[0]] = arrKyValue[1];
})
return objQueryString;
}
objParams = convertToObject(params);
console.log(objParams.val, objParams["val"])
}
Here is Plunker

When it's a string, it's a string. You could parse it to get values based on known format, but there is no way of referencing something inside of the string.
Therefore, it's better to store params in the object for later use and create a string only when you need it, based on that object.
So, it could be like this:
var params = {
val: val,
type: type,
intro: intro
};
then, params.val will be accessible. When you'll need a string, you'd do var string = "type=" + params.type + "&intro=" + params.intro + "&val=" + params.val;

Your params variable is just a string. What you are trying to do is access it like an object.
A better solution would be:
// Create an object
var params = {};
// Create the properties
params.type = "some type";
params.val = "some value";
params.intro = "some intro";
// Alternatively
var params = {
type: "some type",
val: "some value",
intro: "some intro"
};
// Function that does something with your params
function doSomething(input) {
console.log(input.val);
}
// Function that converts your object to a query string
function toQueryString(input) {
var keyValuePairs = [];
for (var key in input) {
if (input.hasOwnProperty(key)) {
keyValuePairs.push(encodeURI(key) + "=" + encodeURI(input[key]));
}
}
return keyValuePairs.join("&");
}
doSomething(params);
console.log(toQueryString(params));
Outputs
some value
type=some%20type&val=some%20value&intro=some%20intro
As a side note, it is generally a bad idea to use words that can be potentially a keyword in your code or in the future (IE: params). A better name would be one that is informative, such as welcomeMessage, introduction or employee (Based off the 3 values you listed)

var params = "" is not a function, its a statement. A function in JS is created by using function(params) = {} or in ES6 you can use =>. When you use += on a sting you are saying "take whatever string is already in params and add on to it what Im about to tell you." After your statement is evaluated you have a new string. Although strings can be accessed like arrays e.g. x = 'hello' and then x[0] would return 'h' where 0 refers to the character at the index of the string. You are trying to use dot notation which is used for JS object literals e.g. x = {prop1: 200, prop2: 300} then x.prop1 would return 200. Or using the array syntax you would do x[prop1] instead.

Do it this way, check demo - fiddle:
var value = false, temp;
params.split('&').forEach( function(item) {
temp = item.split('=');
if(temp[0] === 'val') {
value = temp[1];
}
})
console.log(value);

Related

Access object property name with for loop

I'm working on Emoji system based on JavaScript & Github Emoji icons , I use a function to trigger typing event, that's my code
function myFunction() {
var y = document.getElementById("myInput").value;
var x = y.replace(/plus/g,'<img width="25" src="https://assets-cdn.github.com/images/icons/emoji/unicode/1f44d.png?v7" />');
document.getElementById("demo").innerHTML = "You wrote: " + x;
}
it's working well , but it's not smart .
I tried using an Array with for loop to handle the Github Emoji API
var data = {
star: "https://assets-cdn.github.com/images/icons/emoji/unicode/2b50.png?v7"
};
for (var i in data) {
console.log(data[i]);
}
the for loop access the object property but not display it's name , I need the property name for replacement , the final code I expect is :
for (vari in data) {
var x = string.replace(/${property_name}/g, data[i]);
}
Try this:
for (var key in data) {
if (data.hasOwnProperty(key)) {
var x = string.replace(new RegExp(key, "g"), data[key]);
}
}
When you use a for(var i in data) loop i is the object property not data[i]
Also, if you want to construct a regex pattern from a string you'll have to create a RegExp object.
For completeness, a better way might be to avoid the loop and make use of .replaces ability to take a callback function:
var data = {
star: "https://assets-cdn.github.com/images/icons/emoji/unicode/2b50.png?v7"
};
var pattern = new RegExp(Object.keys(data).join('|'), 'g');
var x = string.replace(pattern, function(match) { return data[match]; });

Convert String to Array update a value and return a string using javascript

I have an string that looks like this separated with ('\n')
car_make:Honda
car_model:Accord
I am trying to build a javascript function that updates the value given and returns the updated string.
function updateCar(car_str, new_car_make, new_car_model){
var car_array = car_str.split('\n');
var new_car_array = new Array();
if(new_car_make){
//update new_car_array i.e new_car_array
}
if(new_car_model){
//update new_car_array i.e new_car_array
}
return new_car_array.toString();
};
so when someone uses the function
updateCar(car_str, 'Acura', 'Integra');
the new output looks like this
car_make:Acura
car_model:Integra
Or if the use they do this:
updateCar(car_str, 'Acura', '');
The output looks like this
car_make:Acura
car_model:Accord
I am not sure why I can't get this it seems so simple. I have done searches but maybe i am not searching the right terms.
var car_str = "car_make:Honda\ncar_model:Accord";
function updateCar(car_str, new_car_make, new_car_model) {
var lines = car_str.split('\n');
var car = {};
lines.forEach(function(line) {
var parts = line.split(':');
car[parts[0]] = parts[1];
});
if (new_car_make) {
car.car_make = new_car_make;
}
if (new_car_model) {
car.car_model = new_car_model;
}
return 'car_make:' + car.car_make + '\ncar_model:' + car.car_model;
};
updateCar(car_str, 'Acura', 'Integra'); // => car_make:Acura\ncar_model:Integra
Not sure if this is useful, but it seems like you'd be better off just adding commas to the end of each line and converting to/from JSON
Edit: You would also have to wrap the values (and maybe the keys) in quotes
It's not necessary to create a new array to store the result of your processing. You can just use the array you make from calling split
function updateCar(car_str, new_car_make, new_car_model){
var car_array = car_str.split('\n');
if(new_car_make){
}
if(new_car_model){
}
return car_array.toString();
};
Since you have a consistent string beign passed in we know what the contents of car_array will be. For example if you pass in
car_make:Honda
car_model:Accord
Your array will look like this
["car_make:Honda","car_model:Accord"]
when we successfully enter one of the if statements we know we have a new value to set in our array. Since we know the structure and contents of our array we can set the new values by index.
function updateCar(car_str, new_car_make, new_car_model){
var car_array = car_str.split('\n');
if(new_car_make){
car_array[0] = "car_make:" + new_car_make;
}
if(new_car_model){
car_array[1] = "car_model:" + new_car_model;
}
return car_array.toString();
};
So if we call updateCar('car_make:Honda\ncar_model:Accord', 'Acura', 'Integra'); during execution our function will look like this:
function updateCar('car_make:Honda\ncar_model:Accord', 'Acura', 'Integra'){
var car_array = 'car_make:Honda\ncar_model:Accord'.split('\n');
if('Acura'){
["car_make:Honda","car_model:Accord"][0] = "car_make:" + 'Acura';
}
if('Integra'){
["car_make:Acura","car_model:Accord"][1] = "car_model:" + 'Integra';
}
return ["car_make:Acura","car_model:Integra"].toString();
which will return "car_make:Acura,car_model:Integra". We can use Array.join(separator) to change how we join the elements in our array. Since we passed in a \n delimited string we can use \n to join the string to get something out that looks like what we put in.
function updateCar(car_str, new_car_make, new_car_model){
var car_array = car_str.split('\n');
if(new_car_make){
car_array[0] = "car_make:" + new_car_make;
}
if(new_car_model){
car_array[1] = "car_model:" + new_car_model;
}
return car_array.join("\n");
};
So now if we call updateCar('car_make:Honda\ncar_model:Accord', 'Acura', 'Integra'); we will get
car_make:Acura
car_model:Integra
And if we pass in a blank string for either parameter we will not enter that particular if statement so the value will remain the same.
Here is one solution, however, are you sure the line deliminator is really "\n" and not a CR or LF? String.fromCharCode(13) or String.fromCharCode(10)
var str="car_make:Honda\ncar_model:Accord";
var delim1 = "\n";
var delim2 = ":";
var formatAttrs= function (attrs) {
return "car_make"+delim2+attrs.car_make+
delim1+"car_model"+delim2+attrs.car_model;
};
var parseStr = function (car_str){
var attrs= {};
car_str.split(delim1).forEach(function(row){
var segments = row.split(delim2);
attrs[segments[0]]=segments[1];
});
return attrs;
};
var updateCar = function (car_str, new_car_make, new_car_model){
var attrs = parseStr(car_str);
attrs.car_make = new_car_make || attrs.car_make;
attrs.car_model= new_car_model|| attrs.car_model;
return formatAttrs(attrs);
};
console.log(updateCar(str, 'Buick', 'Regal'));
console.log(updateCar(str, '', 'Regal'));
console.log(updateCar(str, 'Buick', null));
Returns:
car_make:Buick
car_model:Regal
car_make:Honda
car_model:Regal
car_make:Buick
car_model:Accord

how to remove particular substring from string using id of li in jquery

I have string
0=>zxz##5=>zxzx##5=>zxz##10=>zxz##1=>asdasd##12=>asdsad##10=>asdsad
where 0,5,10 are ids, text are values and ## is delimiter.
I have id and i want to remove id's value
This is my following code, Please check and suggest.
code1
function remove_feature(id)
{
var feature_str = $("#features_post").val();
var feature_string = feature_str.replace(['id=feature_str'],'', 'gi');
window.jQuery("#features_post").val(feature_string);
window.jQuery("#"+id+"").remove();
alert(feature_string);
return true;
}
code2
function remove_feature(id)
{
var feature_str = $("#features_post").val();
var feature_string = feature_str.replace(id,'', 'gi');
window.jQuery("#features_post").val(feature_string);
window.jQuery("#"+id+"").remove();
alert(feature_string);
return true;
}
I have tried both of code but not working
Try this one with jquery : http://jsfiddle.net/h0qtxn7d/
Can also remove same multiple ids.
var k = "0=>zxz##5=>zxzx##5=>zxz##10=>zxz##1=>asdasd##12=>asdsad##10=>asdsad";
var obj = k.split("##");
var removeItem = 5;
alert('Array before removing the element = ' + obj)
obj = jQuery.grep(obj, function(value) {
return value.split('=>')[0] != removeItem;
});
alert('Array after removing the element = ' + obj);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Misread the question, sorry.
To replace each key => value pair within that string you could use regular expressions:
var string = "0=>zxz##5=>zxzx##5=>zxz##10=>zxz##1=>asdasd##12=>asdsad##10=>asdsad";
function remove_feature(id) {
var x = new RegExp("" + id + "\=>[a-z0-9]+(##)?", "gi")
return string.replace(x, "");
}
So, remove_feature(5) prints "0=>zxz######10=>zxz##1=>asdasd##12=>asdsad##10=>asdsad".
If the id parameter is a key which exists in your provided string and the respective name should be returned you could make use of the JSON.parse function pretending to parse a url. Therefore you could replace the delimiters by &s and the => by =s:
var string = "foo=>bar##john=>doe";
function remove_feature(id) {
// id should be something left hand side the =>, like 0 or 1
var _string = string.replace('##', '&').replace('=>', '='),
obj = JSON.parse('{"' + decodeURI(_string).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}'),
_id = obj["" + id];
$('#' + _id).remove();
}
Usage: remove_feature("foo") would remove an element with id #bar.

How to use contents of array as variables without using eval()?

I have a list of variables or variable names stored in an array. I want to use them in a loop, but I don't want to have to use eval(). How do I do this? If I store the values in an array with quotes, I have to use eval() on the right side of any equation to render the value. If I store just the variable name, I thought I'd be storing the actual variable, but it's not working right.
$(data.xml).find('Question').each(function(){
var answer_1 = $(this).find("Answers_1").text();
var answer_2 = $(this).find("Answers_2").text();
var answer_3 = $(this).find("Answers_3").text();
var answer_4 = $(this).find("Answers_4").text();
var theID = $(this).find("ID").text();
var theBody = $(this).find("Body").text();
var answerArray = new Array();
answerArray = [answer_1,answer_2,answer_3,answer_4,theID,theBody]
for(x=0;x<=5;x++) {
testme = answerArray[x];
alert("looking for = " + answerArray[x] + ", which is " + testme)
}
});
You can put the values themselves in an array:
var answers = [
$(this).find("Answers_1").text(),
$(this).find("Answers_2").text(),
$(this).find("Answers_3").text(),
$(this).find("Answers_4").text()
];
for(x=0;x<=5;x++) {
alert("looking for = " + x + ", which is " + answers[x])
}
EDIT: Or even
var answers = $(this)
.find("Answers_1, Answers_2, Answers_3, Answers_4")
.map(function() { return $(this).text(); })
.get();
If your answers share a common class, you can change the selector to $(this).find('.AnswerClass').
If you need variable names, you can use an associate array:
var thing = {
a: "Hello",
b: "World"
};
var name = 'a';
alert(thing[name]);
This would make it easier to get the array populated.
var answers = new Array();
$("Answers_1, Answers_2, Answers_3, Answers_4", this).text(function(index, currentText) {
answers[index] = currentText;
});
As others have mentioned, if you can put the variables in an array or an object, you will be able to access them more cleanly.
You can, however, access the variables through the window object:
var one = 1;
var two = 2;
var three = 3;
var varName = "one";
alert(window[varName]); // -> equivalent to: alert(one);
Of course, you can assign the varName variable any way like, including while looping through an array.

Javascript: Using object's field's value to determine another object literal's field's name

I want to use object's field's value while creating another object using literal notation:
var T = {
fieldName : 'testField'
};
/*
// Doesn't work.
var test = {
T.fieldName : 'value'
};
*/
// Does work.
var test = [];
test[T.fieldName] = 'value';
alert(test.testField); // test
But it doesn't work.
Is there a way to solve this issue or using square brackets is the only way out?
Upd.: Removed non-working code.
var T = {
fieldName : 'testField'
};
var dummy = T.fieldName; // dummy variable
var test = {
dummy : 'value'
};
alert(test.testField); // test
That should not work. The value 'value' will be stored in test.dummy, not test.testField. The way to do it would be:
var T = {
fieldName : 'testField'
};
// Does work.
var test = {};
test[T.fieldName] = 'value';
alert(test.testField); // alerts "value"
Which is what you already have
Your "test" variable is Array, not Object.
You should create "test" like "= {}" instead of "= []".
One possible way is.
var T={
testField : 'testField'
};
eval ('var test = {' + T.testField + ':' + value + '}');
And you make this generic, something like this
function MakeVar(varName,fieldToUse,valueToPass)
{
var res = 'var ' +varName+ '= {' + T.testField + ':' + value + '}'
eval(res);
}
var T={
testField : 'testField'
};
MakeVar('test',T.testField,'value');
var outt=test.testField;
Hope this helps

Categories

Resources