String to number conversion using JavaScript - javascript

This is my html code but the problem is that if I add two strings it always gives the 50 as the addition.
function add()
{
var fname=document.getElementById("fname");
var lname = document.getElementById("lname");
var fstring = fname.toString();
var lstring = lname.toString();
var fl = fstring.length;
var ll = lstring.length;
var f1 = parseInt(fl,10);
var l1 = parseInt(ll,10);
document.getElementById("result").innerHTML = f1 + l1;
}
</script>

Because you are NOT reading the value of the input
var fname=document.getElementById("fname");
var lname = document.getElementById("lname");
var fstring = fname.toString(); //<-- turning object to string
var lstring = lname.toString(); //<-- turning object to string
needs to be
var fname=document.getElementById("fname");
var lname = document.getElementById("lname");
var fstring = fname.value;
var lstring = lname.value;

I think the issue is that you are getting the Element itself, rather than the content of the given element. For example if fname was an input, you'd want to call
var fname=document.getElementById("fname").value;
Current what I'm guessing is happening is that calling toString() on the element itself returns something like [object HTMLInputElement], hence why you always get the same lengths when you do the addition.
If you get the values rather than the elements, your code should then work as expected.

var fstring = fname.toString();
var lstring = lname.toString();
This tries to convert the HTMLElement objects to string, while what you probably want is the value stored in those inputs.
var fstring = fname.value;
var lstring = lname.value;
Also, you don't need to do this:
var fl = fstring.length;
var ll = lstring.length;
var f1 = parseInt(fl,10);
var l1 = parseInt(ll,10);
The length property is a number already.
If you wanted to get the total length of both names, just do
total = fstring.length + lstring.length;
If you wanted to concatenate them, do
fullname = fstring + " " + lstring;
And finally, don't put 1's and small L's in short variable names like that, this can become quite confusing.

Use This
function add(){
var fname=document.getElementById("fname");
var lname = document.getElementById("lname");
var fstring = fname.value.toString();
var lstring = lname.value.toString();
var fullName = fstring +" "+lstring;
alert(fullName )
}
<input type='text' id='fname'/>
<input type='text' id='lname'/>
<input type='button' id='btnOk' onclick='add()' value='OK'/>

Related

How to reverse a string using loops in js

So I created this code and i was wondering how I would be able to loop depending on the amount of spaces there are in the userInput.
var userInput = prompt("Enter a phrase you want to reverse?")
var userOutput = ""
var array = []
var length = userInput.length;
var str = userInput.lastIndexOf(" ")
var test = userInput.substr(str, length);
The main Objective of this program is to reverse the userInput by not using js methods
Input:
"Hello world"
Output:
world Hello
1) Split the string on ' ', save to an array of strings
2) Reverse the array
3) Join the array elements with ' '
var userInput = prompt("Enter a phrase you want to reverse?")
var userOutput = ""
var array = []
var length = userInput.length;
var str = userInput.lastIndexOf(" ")
var test = userInput.substr(str, length);
var reversed = "";
while (length) {
reversed += test[--length];
}
Edit:
Woha! I should have been more careful using test.length instead of input length.
I will leave it for you as an practice to find and fix the bug I made.

Extract john and 5 from this string and store them in a variable

I am new to programming and I have the following string:
var username=Owners|cnt1|john,Status|cnt1|8
I want extract 'john' username will change and 8 from this variable, and store it in two separate variables. Can anyone please help out here
Will this below code work?
var re = /(test\d+)\-(\d+)/g;
var arr = [];
In failed to find test in your string. So do matching the word which exists before , and the last number.
var username = "Owners|cnt1|john,Status|cnt1|8"
s = username.match(/[^|,]+(?=,)|\d+$/g)
var user = s[0];
var pass = s[1];
alert(user);
alert(pass)
You can simply use split() method to do this:
var username = "Owners|cnt1|john,Status|cnt1|8";
var words = username.split("|");
var name = words[2].split(",")[0];
var num = words[4];
alert("Name is: " + name + " and number is: " + num);
And this is a solution with Regex:
var matches = username.match(/(?!\|)(\w+)(?!,)|(?!\|)(\d+)$/g);
var name = matches[0];
var num = matches[1];
console.log("With Regex, Name is: " + name + " and number is: " + num);

Javascript: array.push is undefined

I have my code:
var name = [];
var mark1 = [];
var mark2 = [];
var mark3 = [];
var total = [];
count = 0
count2 = 0
var i = 0;
while (count != 2) {
var nam = prompt("Enter name:")
name.push(nam);
var mk1 = prompt("Enter mark 1:");
var mk1 = parseInt(mk1);
mark1.push(mk1);
var mk2 = prompt("Enter mark 2:");
var mk2 = parseInt(mk2);
mark2.push(mk2);
var mk3 = prompt("Enter mark 2:");
var mk3 = parseInt(mk3);
mark3.push(mk3);
var tot = mk1 + mk2 + mk3;
total.push(tot)
count = count + 1
console.log(mk1 + mk2 + mk3);
console.log(nam);
console.log("the count is " + count)
};
When I run it I get an error:
Uncaught TypeError: undefined is not a function
on Line 12 which is name.push(nam);
I have looked around but I am not sure what I am doing wrong. Help appreciated.
This is an interesting one. It all boils down to an unfortunate choice of variable name. Unfortunately name is a property of the window object. When you refer to name you are actually referring to window.name, not the array called name. If you rename name to something else, it should work just fine.

Access variables like a text?

Let's say i got a variable Var123;
var x = "Var";
var VariableMixLOL = x + "123";
//so VariableMixLOL should be equal to Var123, ex. Var123 = "Abc", VariableMixLOL should be "Abc" too
How can I do this? Btw i'm using as3
PS: Added at Tags JS too because i think it's the same thing
One option is to use eval()
var x = "Var";
var Var123 = "lalaala";
var VariableMixLOL = eval( x + "123" );
Another option and the better one is to model such things in a JavascriptObject.
var x = "variable";
var variables = { "variable123" : "laalala"}; //OR variables = {}; variables["variable123"] = "laalala";
var VariableMixLOL = variables[ x + "123"];
Variable name as String can be used if you incorporate an object to which you store it.
For example:
var x = "Var";
var compoundVar = x + "123";
var obj : Object = {};
obj[compoundVar] = 7;
//Now you can call the variable like this
trace(obj.Var123); //7

Parse out all long/lat from a string

Hi i am trying to get each longitude and latitude that arrives in this format:
(52.99315484540412, -1.179145092694469)(52.99315323095451, -1.1786797294303852)(52.993042641012025, -1.1789238104507405)(52.99308461678997, -1.1791705736801106)
I wish to store them in these strings tmpLon1 tmpLat1 tmpLon2 tmpLat2 tmpLon3 tmpLat3 tmpLon4 tmpLat4
So far i have done this coding but it fails to work, any body have a better method and could code up an example please ?
//(52.99315484540412, -1.179145092694469)(52.99315323095451, -1.1786797294303852)(52.993042641012025, -1.1789238104507405)(52.99308461678997, -1.1791705736801106)
//Remove all the shit
longlat = (longlat.replace(/\(/g,""));
longlat = (longlat.replace(/\)/g,"|"));
longlat = (longlat.replace(/\ /g,""));
//52.99315484540412,-1.179145092694469|52.99315323095451, -1.1786797294303852|52.993042641012025, -1.1789238104507405|52.99308461678997, -1.1791705736801106|
//Now split out each long lat
tmpLon1 = longlat.split(",","1"); //ok
tmpLat1 = longlat.replace(tmpLon1 + ",","");
tmpLon2 = tmpLat1;
tmpLat1 = tmpLat1.split("|","1"); //ok
tmpLon2 = tmpLon2.split("|","2");
tmpLon2 = tmpLon2.replace(tmpLat1,"");
tmpLat2 = longlat.split(",","4");
tmpLon3 = "";
tmpLat3 = "";
tmpLon4 = "";
tmpLat4 = "";
I'd do this:
var a = "(52.99315484540412, -1.179145092694469)(52.99315323095451, -1.1786797294303852)(52.993042641012025, -1.1789238104507405)(52.99308461678997, -1.1791705736801106)",
latLngs = [],
pairs = a.replace(/^\(|\)$/g,'').split(')(');
for(var i=0,pair;pair=pairs[i];i++) {
pair = pair.split(',');
latLngs.push({lat: +pair[0], lng: +pair[1]});
}
console.log(latLngs);
you can see it live here: http://jsfiddle.net/LCYrg/
You could also simply do:
var a = "(52.99315484540412, -1.179145092694469)(52.99315323095451, -1.1786797294303852)(52.993042641012025, -1.1789238104507405)(52.99308461678997, -1.1791705736801106)",
JSON.parse(a.split(')(').join('],[').replace('(','[[').replace(')',']]'));
But this would require the JSON object to be present, which is not the case in ie7 and below. This could be fixed by including the json2.js file found here: https://github.com/douglascrockford/JSON-js
Regex to the rescue! Since you know the format of your string, you can use regex here to search for you.
var str = "(52.99315484540412, -1.179145092694469)(52.99315323095451, -1.1786797294303852)(52.993042641012025, 1.1789238104507405)(52.99308461678997, -1.1791705736801106)";
var regex = /\((-?[0-9]+\.[0-9]+), (-?[0-9]+\.[0-9]+)\)/g;
var latlonArray = [];
var match = regex.exec(str);
while (match) {
latlonArray.push({
"lat" : match[1],
"lon" : match[2]
});
match = regex.exec(str);
}
var tmpLon1 = latlonArray[0].lon;
var tmpLat1 = latlonArray[0].lat;
var tmpLon2 = latlonArray[1].lon;
var tmpLat2 = latlonArray[1].lat;
var tmpLon3 = latlonArray[2].lon;
var tmpLat3 = latlonArray[2].lat;
var tmpLon4 = latlonArray[3].lon;
var tmpLat4 = latlonArray[3].lat;
Example: http://jsfiddle.net/jonathon/57rE4/
The latlonArray is an array of objects with lat and lon properties, containing the ones found in your string.
Note: the regex I used here is just something I came up with. It works with your example input but might not necessarily be the best.
Also note: this isn't meant to be 'pull out and use' JavaScript. It's merely showing you another way to do it. I'd recommend optimising it by various means (e.g. moving all vars to the top, etc).
i guesy u can do something like:
(assuming input is your input string)
input = input.replace(/\s/,''); //remove spaces
var pairs_strings = input.substring(1,-1).split(")("); //remove braket of start and end and then split into pairs
var pairs = new Array();
for(var i=0; i<paris_strings.length; i++){
lon = pairs_strings[i].split(",").shift();
lat = pairs_strings[i].split(",").pop();
pairs[i] = new Array(lon, lat);
}
var tmpLon1 = pairs[0][0];
var tmpLan1 = pairs[0][1];
....
but be aware it's not tested and i don't know what will happend with the negative values
If your input format is not changing you could do it in 3 lines:
var str = "(52.99315484540412, -1.179145092694469)(52.99315323095451, -1.1786797294303852)(52.993042641012025, -1.1789238104507405)(52.99308461678997, -1.1791705736801106)";
var pattern = /([\d\.-]+),\s([\d\.-]+)\)\(([\d\.-]+),\s([\d\.-]+)\)\(([\d\.-]+),\s([\d\.-]+)\)\(([\d\.-]+),\s([\d\.-]+)/;
var result = str.match(pattern);
To get the results use:
tmpLon1=result[1];
tmpLon2=result[3];
tmpLon3=result[5];
tmpLon4=result[7];
tmpLat1=result[2];
tmpLat2=result[4];
tmpLat3=result[6];
tmpLat4=result[8];
var str = "(52.99315484540412, -1.179145092694469)(52.99315323095451, -1.1786797294303852)(52.993042641012025, -1.1789238104507405)(52.99308461678997, -1.1791705736801106)";
var str = str.replace(/\)\(/g,', ').replace(/\(|\)/g,'').split(", ");
To get the results:
tmpLon1=result[0];
tmpLon2=result[2];
tmpLon3=result[4];
tmpLon4=result[6];
tmpLat1=result[1];
tmpLat2=result[3];
tmpLat3=result[5];
tmpLat4=result[7];

Categories

Resources