variable string appearing as undefined, new string not appearing in array, javascript - javascript

I'm attempting to write some code that puts a single string of emails into an array of emails. Splitting the string wherever there's a comma(,). The initial problem i'm having is the string that is being passed as a variable is not being recognized. I'm getting the error message "Cannot read property 'length' of undefined" of the conditional part of the for loop. Odd, as I'm definitely passing a string or trying to ?
When I pass in a string directly to the function parameter(to avoid the above problem for testing the rest of the function) only the first 2 email addresses appear the final email address is lost ?
I'm learning programming and this is an exercise as such I'm trying to avoid using the split() method or regEx. Daft i know.
Any help in overcoming these 2 issues greatly appreciated.
function separateCommaValues(text)
{
var input = [];
var val = '';
for(var i = 0; i < text.length; i++) {
if(text[i] == ',') {
if(val.length == 0){
continue;
}
input.push(val);
val = '';
} else {
val += text[i];
}
}
document.write( input );
}
separateCommaValues(str);
var str = "john#google.com, jake#yahoo.com, andrew#hotmail.com";

var str = "john#google.com, jake#yahoo.com, andrew#hotmail.com";
separateCommaValues(str);
This is the correct order. Your variable can be declared before it is used via hoisting, but you can't define it before it is used (undefined error).

And the last email address isn't pushed into the array because it doesn't have a comma after it. So after the loop, before document.write( input );, add something like this:
if(val.length > 0){
input.push(val);
val = '';
}

Related

Is it possible to construct a string in Javascript which has 'variables' built in?

I am working on a PDF with some scripting, and I am applying code to fields using the console and some simple loops to save on repeated efforts. In some cases, I am applying a custom calculation script to a field where one integer needs to change from one field to the next. If all the scripts were the same, I would run this in the debugger console:
var s = "if(this.getField(\"Span A\").value >= 60){\n\
event.value = Math.round(((this.getField(\"Span A\").value*41500 - 1674500)/233));\n\
}else{\n\
event.value = Math.round((this.getField(\"Span A\").value*3500/60));\n\
}";
for (var i = 0; i < this.numFields; i++){
var f = this.getField(getNthFieldName(i));
if(f.name.match(/quant a/i) != null){
var n = f.name.match(/\d/g);
f.setAction("Calculate", s);
}
}
I have many 'Quant' fields, and each group (A, B, etc) will have a similar calculation. The fields are name "Quant A1", "Quant A2" etc. Quant A1 needs to calculate with the input from Span A1.
In the above script, it would be really cool if I could have a variable within the script string that I can pass a value (n) to be plugged in to the string, essentially the same way a function call works.
Is this possible?
Here is my fantasy version of what I imagine it could look like (this is just to further explain my intent; I don't think this would actually work this way):
var s(x) = "if(this.getField(\"Span A\""x").value >= 60){\n\
event.value = Math.round(((this.getField(\"Span A\""x").value*41500 - 1674500)/233));\n\
}else{\n\
event.value = Math.round((this.getField(\"Span A\""x").value*3500/60));\n\
}";
for (var i = 0; i < this.numFields; i++){
var f = this.getField(getNthFieldName(i));
if(f.name.match(/quant a/i) != null){
var n = f.name.match(/\d/g);
f.setAction("Calculate", s(n));
}
}
You could use string litterals if you're useing ES6 and higher.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals?retiredLocale=nl
const greetings = "I'm a variable!";
let string = `Hi! this is a variable: ${greetings}`;
console.log(string);
Otherwise concatenate it with the + operator.
If I understand correctly your question. I think you want to use template literals.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
Use backticks instead of " or ' to insert your variables inside a string.
const a ='Cheese'
const b= 'is Delicious'
${a} ${b} will output 'Cheese is Delicious'

Compare two variable string in JavaScript

i am trying to compare two strings in javascript. below is my code
var statuss = document.getElementById("status").innerHTML;
//alert(statuss);
var s =statuss.toString();
var ss= "Active";
if (s === "Active"){
alert ('match');
}
else {
alert ('do not match');
}
why am i getting the output " do not match" when it should have been 'match' since when i did
alert ('document.getElementById("status").innerHTML');
i got the output: Active.
So basically both variable should have matched.. why am getting the opposite?
You might want to try the following
var s = statuss.toString().trim();
The most likely explanation is that your HTML also contains whitespace at the beginning and/or end.

Make javascript as function

i could not make it as function.Please help.When i modified as function and add button,it not work.
i'm newbie in javascript.i would like study by the simple script.But for the below script when i try to add "function xxx()" it not working with input button.
I try to solve by my own with google...failed.
<script>
var myStr = "xxx yyy zzz";
var strArray = myStr.split(" ");
// Display array values on page
for(var i = 0; i < strArray.length; i++){
document.write("<p>" + strArray[i] + "</p>");
}
</script>
Break your code into blocks if you ever are stuck on something. So first you are trying to break a string into an array so that's your first block. Then your second block would be to write it to the page. So we have our code basically written out in our heads.
---Break string
---Display broken string
So to make a function we need to write a function first
myFunction = function(){
};
But to get the function to be modular we need to be able to pass in variables
So we'll add two variables one being the string to pass through and one being the location to inject the looped broken text.
myFunction = function(str, location){
};
Now we have to do something with these variables.
myFunction = function(str, location){
///test if str is a string
if(typeof(str) == "string")
{
var l = str.split(" "); /// here we're spliting the string into an array by every space
if(l.length >= 1) ///test if there's atleast one item
for(i=0;i<l.length;i++) ///simple for loop
location.innerHTML += "This is a part of str " + l[i] + "<br>" ///you can do anything here you want to do.
}
};
Now as you can see it's modular at it's lowest point, this can be as complex as you want it. here is a test you can try out and mess around with. https://jsfiddle.net/s8pytzm3/1/

Cant get indexOf statement to work

Ultimately I am prompting the user for a guess, which is then ultimately changed so regardless of what the user inputs it will always Capitalize the first letter and make the rest lowercase. (Im doing this so if the user types in a guess the string will either match or not match the values in an array.) I tried doing a for statement to use a loops counter (3 total guesses is what im looking for). But when I try to use a indexOf to check the array, I keep getting an "unexpected token" error on that line that contains the indexOf statement. So the question would be (1) what am i doing wrong in this line of code?
//declare variables
var sportsArray = new Array("Football", "Basketball", "Rollerblading", "Hiking", "Biking", "Swimming");
var name = prompt("Enter your name");
var loops = 0;
var score = 0;
var sGuess = prompt("enter your sport guess");
// uses substrings to ultimately capitalize the 1st letter, and make everything after it lowerCase.
var sFirstPart = sGuess.substr(0, 1);
var sFirstCap = sFirstPart.toUpperCase();
var sSecondPart = sGuess.substring(1, sGuess.length);
var sSecondLow = sSecondPart.toLowerCase();
var usableGuess = sFirstCap + sSecondLow;
while(loops < 4){
if(sportsArray.indexOf(usableGuess) = 0 {
document.write("nice guess");
loops++;
}else {
document.write("loser");
loops++;
}
}
This works for checking the whole array:
var sportsArray = new Array("Football", "Basketball", "Rollerblading", "Hiking", "Biking", "Swimming");
var name = prompt("Enter your name");
var loops = 0;
var score = 0;
var sGuess = prompt("enter your sport guess");
// uses substrings to ultimately capitalize the 1st letter, and make everything after it lowerCase.
var sFirstPart = sGuess.substr(0, 1);
var sFirstCap = sFirstPart.toUpperCase();
var sSecondPart = sGuess.substring(1, sGuess.length);
var sSecondLow = sSecondPart.toLowerCase();
var usableGuess = sFirstCap + sSecondLow;
while(loops < 4){
if(sportsArray.indexOf(usableGuess) > -1) {
document.write("nice guess");
loops++;
}else {
document.write("loser");
loops++;
}
}
You'd want to use indexOf(guess) > -1 to check if the guess is present at any index of the array. For checking just one index position it would be indexOf(guess) == 0.
sportsArray.indexOf(usableGuess) === 0) instead of sportsArray.indexOf(usableGuess) = 0
It's a good practice to check for equality with constant on the left side. It will throw an exception in most browsers:
var a = 3;
if (12 = a) { // throws ReferenceError: invalid assignment left-hand side in Firefox
//do something
}
Also: use tools that provide static code analysis. A jslint.com or jshint.com for js is a good choice. There are also IDE plugins explicitely for that (using either of those two and more), see Is there a working JSLint Eclipse plug-in?.

Printing PHP string using JQuery

I got a script which uses an array that was created in PHP and was encoded to JSON. It then take the string and use it to set a value for an element I created:
var val ="";
if(arr != null)
{
if((arr[i] != undefined) && (arr[i]["value"] != undefined))
{
var val = JSON.stringify(arr[i]["value"]);
val.replace(/"/g , "");
}
}
cell.innerHTML = "<input type='text' value='"+val+"' style='padding-right: 0px;'/>";
The problem is that every string on the screen appears with the "" around the string itself. for example "5". I want it to be just 5 and not "5". I thought the replace I did to the val was supposed to do it but it didn't work. why is that?
OK the problem is just something I keep forgetting all the time.
The line val.replace(/"/g , ""); is missing its magic and should be:
val = val.replace(/"/g , "");
I'm leaving the question so other people might be able to see how to decode a JSON string and how to use an array which was created in PHP.

Categories