This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Copying array by value in javascript
I am a beginner with javascript, so I would really appreciate any help or advice. I'm trying to get the values that I collect with my inputs array (that are put into a form, by the user, in the document) to set them to the words array. So, I would like inputs[0] = words[0], inputs[1] = words[1] etc. I thought by setting words to an empty array, and then to equal the index value of inputs, that I would achieve this, but it's not working. Words keeps showing up as "undefined".
function goMad() {
var words = [];
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length - 1; i++) {
inputs[i].value = words;
}
var story = words[0] + "! he said " + words[1] + " as he jumped into his convertible " + words[2] + " and drove off with his " + words[3] + " wife.";
document.getElementById("story").innerHTML = story;
console.log(words[0]);
}
Instead of this line:
inputs[i].value = words;
You can use:
words.push(inputs[i].value);
This will add the provided value to the words array. See the MDN docs.
As #pimvdb and #Shmiddty have pointed out you could also use the following. This would behave exactly the same as using push:
words[i] = inputs[i].value;
Related
I have a loop that will declare a new variable each time. I want to write my results to a new window and I would like every string declared to print with breaks.
I did try making combining all vars together with '+' signs (using [i] to get the number of occurrences) but document.write printed it because it was a string.
Does anyone know what I can do? I'm sure there must be a few ways but I've been stuck on this for a while.
window['question'+i] = "some stuff";
var myWindow = window.open("", "Questions", "width=500,height=600");
myWindow.document.write(
question0 + ("<br>") +
question1 + ("<br>") +
question2 + ("<br>") +
question3 + ("<br>")
...
)
I recommend to not use different variables. Array's are made for these kind of things and provide functions to do this a lot easier. See this snippet below how to store the texts from a loop in an array and easy print it splitted by a <br> using the join function.
var values = new Array();
for (var i = 0; i < 10; i++) {
values.push("<span>value " + i + "</span>");
}
document.getElementById('result').innerHTML = values.join("<br>");
//If you really want to use document.write()
//document.write(values.join("<br>"));
<div id="result"></div>
I have a sentence stored in a variable.That sentence I need to extract into 4 parts depends on sentence which I have put into variables in my code,I can able to extract here and get into console but I am not getting the whole text of inside the bracket,only I am getting first words.Here is the code below.Can anyone please help me.
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="messages">
SCRIPT
$(document).ready(function() {
regex = /.+\(|\d. \w+/g;
maintext = "Welcome to project, are you a here(1. new user , 2. test user , 3. minor Accident or 4. Major Accident)";
matches = maintext.match(regex);
text_split0 = matches[0].slice(0, -1);
text_split1 = matches[1];
text_split2 = matches[2];
text_split3 = matches[3];
text_split4 = matches[4];
console.log(text_split0);
console.log(text_split1);
console.log(text_split2);
console.log(text_split3);
console.log(text_split4);
$(".messages").append('<li>'+text_split0+'</li><li>'+text_split1+'</li><li>'+text_split2+'</li><li>'+text_split3+'</li><li>'+text_split4+'</li>');
// $("li:contains('undefined')").remove()
});
function buildMessages(text) {
let messages = text.split(/\d\.\s/);
messages.shift();
messages.forEach((v)=>{
let msg = v.replace(/\,/,'').replace(/\sor\s/,'').trim();
$('.messages').append(`<li>${msg}</li>`);
// console.log(`<li>${msg}</li>`);
});
}
let sentenceToParse = "Welcome to project, are you a here(1. new user , 2. test user , 3. minor Accident or 4. Major Accident)";
buildMessages(sentenceToParse);
Use the split function on the String, keying on the digits (e.g. 1.), you will get the preface and each of the steps into an array.
Use the shift function on the Array removes the unneeded preface.
Use forEach to iterate over the values in the array, clean up the text.
Using replace to first remove commas, then remove or with spaces on either side.
Use trim to remove leading and training whitespace.
At this point, your array will have sanitized copy for use in your <li> elements.
If you're only concerned with working through a regex and not re-factoring, the easiest way may be to use an online regex tool where you provide a few different string samples. Look at https://www.regextester.com/
Ok, Try another approach, cause regex for this isn't the best way. Try this:
$(document).ready(function() {
// First part of sentence.
var mainText = "Welcome to project, are you a here(";
// Users array.
var USERS = ['new user', 'test user', 'minor Accident', 'Major Accident'];
var uSize = USERS.length;
// Construct string & user list dynamically.
for(var i = 0; i < uSize; i++) {
var li = $('<li/>').text(USERS[i]);
if(i === uSize - 1)
mainText += (i+1) + ". " + USERS[i] + ")";
else if(i === uSize - 2)
mainText += (i+1) + ". " + USERS[i] + " or ";
else
mainText += (i+1) + ". " + USERS[i] + " , ";
$(".messages").append(li);
}
console.log(mainText); // You will have you complete sentence.
}
Why that way is better? Simple, you can add or remove users inside the user array. String together with your user list will be updated automatically. I hope that help you.
This question already has answers here:
Access Javascript variables dynamically
(4 answers)
Closed 8 years ago.
I know there are a lot of questions about if it is possible to use variable variables in jQuery.
One of the questions is this one: click here.
I tried to use the answer, but I don't know how I can use it in my case.
var numberofquestions = 10;
var dataString = "";
for ( var i=1; i<=numberofquestions; i++ ) {
/* ------ first part ------- */
if (i==1) {
dataString = dataString + "q1=" + question1 + "&";
} /* ------ end first part ------- */
else if (i == numberofquestions) {
questionValue = "question" + numberofquestions;
qValue = "q" + numberofquestions;
dataString = dataString + qValue + "=" + questionValue;
console.log(dataString);
} else {
questionValue = question + i;
dataString = dataString + "q" + i + "=" + questionValue + "&";
}
}
The loop will run 10 times, and each time it needs to add a part to the already existing dataString.
What it needs to do is make this string:
q1=(value of var question1)&q2=(value of var question2) and so forth.
The vars question1, question2, ... question10 all hold a number.
The first part works, it outputs q1=5 in the console log, however, after comes a random string. The output string (the total string) looks like:
q1=5&q2=NaN&q3=NaN&q4=NaN&q5=NaN&q6=NaN&q7=NaN&q8=NaN&q9=NaN&q10=question10
Does anybody know what I'm doing wrong?
You should use an array for this. There is no such thing as "variable variables" in JavaScript.
You can access a variable through a string containing the variables name by using this[variableName], but again, you shouldn't. You should use an array for this.
In your case, you would use questionValue = this["question" + i], but one more time: Don't do it. Use an array instead.
I'm not sure why you're using "question" + numberofquestions which will be 10 every time
This should be a quickie, but I'm scratching my head as to why this bit of JavaScript isn't working for me. The goal is to take the value of an input box (string of words separated by spaces), list these words as items in an array, and remove those which are fewer than 3 characters:
var typed = $('input').val();
var query = typed.split(" ");
var i=0;
for (i=0; i<query.length; i++) {
if (query[i].length < 3) {
query.splice(i,1);
}
}
Have this running onkeyup for the input box and it seems to work, but only about 50% of the time (strings of 1 and 2 characters somehow find their way into the array on occasion). Any suggestions would be hugely appreciated.
The problem is that you are iterating while removing the elements. Consider this array:
["he", "l", "lo world"]
Initially your loop starts at index 0 and removes "he" from the array. Now the new array is
["l", "lo world"]
In the next iteration i will be 1, and you will check "lo world"'s length, thus ignoring the "l" string altogether.
Use the filter method in Array to remove the unwanted elements.
var biggerWords = query.filter(function(word) {
return word.length >= 3;
});
Besides the iterating problem, you may also see unexpected entries if you type multiple spaces
try
var query = typed.split(/\s+/);
This way it will split on any number of spaces, instead of each individual one
The problem is that you're slicing the array while counting forward. Think about it...if you take an index point out of the array, thereby shortening it by one, incrementing i and moving on to the next one actually moves one further than you want, completely missing the next index. Increment i--, start at query.length-1, and make the condition that i>=0. For an example of this in action, check it out here:
http://jsfiddle.net/kcwjs/
CSS:
input {
width:300px;
}
HTML:
<input id="textbox" type="text" />
<div id="message"></div>
Javascript:
$(document).ready(function() {
$('#textbox').keyup(checkStrings);
});
function checkStrings(e) {
var typed = $('#textbox').val();
if (typed == "") return false;
var query = typed.split(" ");
var querylen = query.length;
var acceptedWords = '';
var badWords = '';
for (var i = querylen-1; i >= 0; i--) {
if (query[i].length < 3) {
badWords += query[i] + " ";
} else {
acceptedWords += query.splice(i,1) + " ";
}
}
$('#message').html("<div>Bad words are: " + badWords + "</div>" +
"<div>Good words are: " + acceptedWords + "</div>");
}
Try this code, it get's rid of any 3 character words, as well as making sure no empty array elements are created.
typed.replace(/(\b)\w{1,3}\b/g,"$1");
var query = typed.split(/\s+/);
hey i think you should use a new array for the result. since you are removing the element in array. the length is changed. here is my solution
var typed = "dacda cdac cd k foorar";
var query = typed.split(" ");
var i=0;
var result = [];
for (i=0; i<query.length; i++) {
if (query[i].length >= 3) {
result.push(query[i]);
}
}
Ok I've been asking alot of JS questions lately, and realized I just need to go learn it.
Been following tutorials at http://www.tizag.com/javascriptT very simple and straightforward.
I just want to make sure I understand this correctly. It took me a while to get it:
<script type="text/javascript">
var myString = "zero one two three four";
var mySplitResult = myString.split(" ");
for(i = 0; i < mySplitResult.length; i++){
document.write("<br /> Element " + i + " = " + mySplitResult[i]);
}
</script>
-
var myString = "zero one two three four";
Obviously that creates a simple string variable.
var mySplitResult = myString.split(" ");
That splits it using " " as the delimeter, and assigns it to the mySplitResult array. Correct? Or is it not an array?
for(i = 0; i < mySplitResult.length; i++){
Is this saying the number of values in the array? Doesn't seem like it could be saying the actual length of characters in the string.
document.write("<br /> Element " + i + " = " + mySplitResult[i]);
This just returns mySplitResult[i] variable "i". Since i is increasing with each loop, it pulls the correct information from the array.
Your understanding is essentially correct. One thing you should do is declare all your variables: this is particularly important inside functions. So, you should declare i as a variable, either before the loop:
var i;
for (i = 0; i < mySplitResult.length; i++) {
... or in the first expression in the for statement:
for (var i = 0; i < mySplitResult.length; i++) {
Your analysis is correct, but you should see that by just testing it. Use Firebug extension with Firefox and you can step through your javascript.
This will help you understand what is going on, as you can then look at properties of the element and monitor what is actually happening.