I am trying to do something like the below but merge function has a problem with the line
content = content.replace( content, "Hi" + values.first_name + "! Thanks for completing this code challenge :)" );
Filename : app.js
var utilities = require("./utilities");
var mailValues = {};
mailValues.first_name = "Janet";
var emailTemplate = "Hi %first_name%! Thanks for completing this code challenge :)";
var mergedContent = utilities.merge(emailTemplate, mailValues);
//mergedContent === "Hi Janet! Thanks for completing this code challenge :)";
Filename : utilities.js
function merge(content, values) {
content = content.replace( content, "Hi" + values.first_name + "! Thanks for completing this code challenge :)" );
return content;
}
module.exports.merge = merge;
Your merge function is not good, it does a weird thing and will surely returns a weird string if you pass another template. You're replacing the entire input string by the "Hi...." string but with first_name inserted so in the end, your function is too specific and can't handle extra parameters or another template/string.
function merge(content, values) {
// loop over all the keys in the values object
Object.keys(values).forEach(function(key) {
// look for the key surrounded by % in the string
// and replace it by the value from values
content = content.replace('%' + key + '%', values[key]);
});
return content;
}
var mailValues = {};
mailValues.first_name = "Janet";
mailValues.last_name = "Doe";
var emailTemplate = "Hi %first_name% %last_name%! Thanks for completing this code challenge :)";
var mergedContent = merge(emailTemplate, mailValues);
document.write(mergedContent);
Try the "run code snippet" button.
for ... in version, for information, better to use the previous version.
function merge(content, values) {
// loop over all the keys in the values object
for (var key in values) {
// look for the key surrounded by % in the string
// and replace it by the value from values
content = content.replace('%' + key + '%', values[key]);
}
return content;
}
var mailValues = {};
mailValues.first_name = "Janet";
mailValues.last_name = "Doe";
var emailTemplate = "Hi %first_name% %last_name%! Thanks for completing this code challenge :)";
var mergedContent = merge(emailTemplate, mailValues);
document.write(mergedContent);
Related
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);
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
I have a file that looks like so:
QUERY:1
DATABASE:geoquery
NL:What are the capitals of the states that border the most populated states?
SQL:something
QUERY:2
DATABASE:geoquery
NL:What are the capitals of the states bordering New York?
SQL:SELECT state.Capital FROM state JOIN borderinfo ON state.State_Name = borderinfo.State_Name
WHERE borderinfo.Border = 'New York'
QUERY:3
DATABASE:geoquery
NL:Show the state capitals and populations.
SQL:SELECT state.Capital, state.Population FROM state
etc...
The person generating this file refuses to give it to me in a usable format like say, XML or JSON. So I am parsing it a couple of times with REGEX to get results I want.
Strip off Databases to populate select list (works fine):
$.get('inputQueryExamples.txt',
function(data){
var string = data;
var dbDynamo ='';
dbExp = new RegExp('(DATABASE:.*)','gm');
dbDynamo = string.match(dbExp);
cleanBreaks = new RegExp('(\r?\n|\r)','gm');
stringNow = dbDynamo.toString();
//console.log(dbDynamo);
dbDynamo = dbDynamo.map(function(el){return el.replace('DATABASE:','');});
var outArray = [];
for(i=0; i < dbDynamo.length; i++){
if ($.inArray(dbDynamo[i],outArray)== -1){
outArray.push(dbDynamo[i]);
}
}
dbDynamo = outArray.sort();
var options = '';
for(i=0; i<dbDynamo.length; i++){
options += '<option value="' + dbDynamo[i] + '">' + dbDynamo[i] + '</option>';
};
$(select).append(options);
});
The problem comes when I parse a second time to get all of the strings associated with a specific database. I end up with a linebreak in front of every string so that when I fill a textarea with the autocomplete text it starts on the second line:
Array [ "
NL:Show company with complaint against Debt collection product.,DATABASE:consumer", "
NL:Show issues and dates of complaints about HSBC companies.,DATABASE:consumer", "
NL:Show companies, issues and dates with consumer concerns.,DATABASE:consumer", "
NL:Show issues and companies with complaints in MA state." ]
$(document).ready(function(){
$.get('inputQueryExamples.txt',function(data){
var queryString = data;
var cleanString = "";
var db = '';
$('#database-list').change(function(){
db = $('#database-list').val();
// /(^DATABASE:.*\r\n)(^NL.*)/gm
// http://regex101.com/r/mN4hS2
regex = new RegExp('(^DATABASE:'+ db +'\r\n)(^NL.*)' ,'gm');
cleanString = queryString.match(regex);
//console.log(cleanString);
//cleanBreaks = new RegExp('(\r\n|\r|\n)(^NL.*)','gm');
//stringNow = cleanString.toString();
//var dirtyString
//dirtyString = stringNow.match(cleanBreaks);
//console.log(dirtyString);
var nlString = cleanString.map(function(el) {return el.replace('DATABASE:' + db,'');});
nlString = nlString.map(function(el){return el.replace('NL:',''); });
//nlString = nlString.map(function(el){return el.replace('\\r','').replace('\\n','');});
console.log(nlString.pop());
$('#query-list').autocomplete({
source:nlString,
});
}); // end change
I have tried about everything I can think of to get rid of the linebreaks without success. Any ideas would be appreciated. Unfortunately the one where the server side just gives me data in a usable format is not viable. There is a lot of extra code in this just to give you an idea of what I have tried. I have commented out useless things. Thanks in advance.
It would make sense to use JavaScript to parse the data-structure you are given into a JavaScript object first, then you can more easily work with the data.
Here is a jsfiddle that demonstrates parsing your data into a JavaScript object. Below is the relevant code that does the parsing:
var datasources = {};
var parseData = function(block) {
var db = block.match(/DATABASE:(.*)/)[1];
var dbdata = {id: 0, nl: "", sql: ""};
if (!datasources[db]) {
datasources[db] = [];
}
dbdata.id = block.match(/QUERY:(.*)/)[1];
dbdata.nl = block.match(/NL:(.*)/)[1];
dbdata.sql = block.match(/SQL:(.*)/)[1];
datasources[db].push(dbdata);
};
var parseBlocks = function(data) {
var result = data.split('\n\n');
for(var i=0; i < result.length; i++) {
parseData(result[i]);
};
};
Thanks for the very thoughtful and elegant approach. I continued the brute force approach.
replace:
nlString = nlString.map(function(el){return el.replace('NL:',''); });
with:
nlString = nlString.map(function(el){return el.replace('NL:','').trim(); });
I need help print and save element in an array in javascript. I know that I have to create an array, and then use a for-loop to save and print it, but i don't know how. What i want to do i so make a simple currency converter, use a for-loop with an array to save the converted input and display it. Here is my code:
JAVASCRIPT
var input = document.querySelector("#input");
var convert = document.querySelector("#convert");
var dollar = 0.51;
var euro = 0.11;
omvandla.onclick = function (){
if(isNaN(input.value)){
alert ("Use numbers");
}
else{
console.log(("Dollar:" + input.value*dollar) + ("Euro:" + input.value*euro));
}
};
HTML
<p>
<form>
<label>Kronor: <input type="text" id="kronor"/></label>
<br><input type="submit" id="convert" value="Omvandla"/>
</from>
</p>
How can I append the converted value after the submit button?
If you want to display one Conversion Result after another, you could do this like this:
var input = document.querySelector("#kronor");
var convert = document.querySelector("#convert");
var dollar = 0.51;
var euro = 0.11;
var conversionArray = [];
convert.onclick = function (){
if(isNaN(input.value)){
alert ("Use numbers");
}
else{
var dollarResult = input.value*dollar;
var euroResult = input.value*euro;
var newArrayEl = {
dollar: dollarResult,
euro: euroResult
};
conversionArray.push(newArrayEl);
console.log(conversionArray);
document.getElementById("convertedValue").innerHTML = "Dollar: " + dollarResult + " Euro: " + euroResult + "<br>" + document.getElementById("convertedValue").innerHTML;
}
};
Then you can access single values of the conversion by e.g. conversionArray[indexOfElement].dollar
This way you don't need an array to store the values. If you really need thos wvalues again, let me know, and im showing you how to store the array.
Here is a Fiddle, that shows how it works.
In javascript the way you add elements to an array is the push function
var myArray = [];
myArray.push(15);
Then to loop through the elements you can do something like this
for(var elem in myArray){
//Do something with elem
}
From your problem description it is hard to figure out what you are trying to do with your code. Hopefully this will help with array manipulation
You can add an element to the end of an array by using the array.push() function. I your example you would do something like:
array = [];
...
omvandla.onclick = function (){
if(isNaN(input.value)){
alert ("Use numbers");
}
else{
console.log(...);
array.push(input.value);
}
};
For more information about JavaScript arrays see here.
I making one application which contains 2 input box and one input button.My qestion is when user enter some input eg. "I used to going somewhere" then my result should be "I UD GNG somewhere." For that i am using this code http://pastebin.com/vHkhASdZ
Please,anyone have idea how to solve then pls reply me asap. I solved my issue in php but in case of javascript i don't have any idea. Here is my output link in php http://codepad.viper-7.com/SQvO6Y
I want my result in javascript.Pls anyone know then give reply.
Use this function
var replaceText = function () {
var inputval = document.getElementById('first_text').value;
var arr = {
"going": "GNG",
"used to": "UD",
"as soon as possible": "ASAP",
"to do fast": "tdf"
}
for(var key in arr) {
if (typeof (arr[key]) !== "undefined") inputval = inputval.replace(key, arr[key])
}
document.getElementById("second_text").value = inputval;
}
Do something like this. Define word replace as map.
var wordmap = {
going: 'GNG',
'used to': 'UD',
'as soon as possible': 'asap',
'to do fast': 'tdf',
..
}
and define function that iterates every word in the input string.
function replace( text ) {
var input = text.split(' ');
var outputval = []
for (var i in input) {
outputval.push( wordmap[input[i]] || input[i] )
}
return outputval.join(' ');
}
And use it like this
var output = replace( document.getElementById('first_text').value );