get the value of a var in the script - javascript

var first = "a whole lotta stuff";
var second = "first";
document.querySelector("input").value = second;
right now the value of the input will be "first". I want it to be "a whole lotta stuff".
in other words, I want the value of the input to be the var first and not just a string of "first".

Based on the additional information you provided in your comment:
var nameNum = "name" + productNum;
document.querySelector("[name=name]").value = nameNum;
//there are vars name1, name2, etc..
//when I ran it I got value="name2"
You need change the way you try and access the variables name1, name2, etc.
The solution is to nest name1 and name2 inside an object and access the keys by building the string within bracket notation. Like this: names['name' + productNum];
Check out this example:
var names = {
name1: 'foo',
name2: 'bar',
}
var productNum = 2
document.querySelector('input').value = names['name' + productNum];
<input type="text">

I removed double quotes around first in second line.
var first = "a whole lotta stuff";
var second = first;
document.querySelector("input").value = second;
Including double quotes makes "first" a string that is assigned to second. Without quotes first is a reference and the value of first is assigned (copied) to second.

Related

Check if array includes a value [in an efficient way]

I have a variable consisting of multiple sentences separated with dots named var a. Then I want to check if Result value is equal to one of the sentences on var a:
Here is the code:
var a = "my name is jack. your name is sara. her name is joe. his name is mike";
var nameSplit = a.split(".");
console.log(nameSplit.length);
console.log(nameSplit);
var Result = "his name is mike";
var i;
for (i = 0; i < nameSplit.length; i++) {
if (nameSplit[i].includes(Result)) {
console.log("Result is one of the sentences on var a");
}
}
The code works fine .
The problem is I have no idea if this code works fast and efficient if I have 1000 sentences or 10000 sentences on var a?
Is there any modification that makes the code faster to execute?
Is there any better solution to do this?
You can use Array.prototype.includes to check if an array includes a string. or String.prototype.includes to match a substring.
var a = "my name is jack. your name is sara. her name is joe. his name is mike";
var nameSplit = a.split(". ");
var Result = "his name is mike";
nameSplit.includes(Result) // true
or
var a = "my name is jack. your name is sara. her name is joe. his name is mike";
var Result = "his name is mike";
a.includes(Result) // true
You need to ask yourself how many substring you want to find in a, if just one, then you dont need to split as split itself takes time and space. (If interested , you can further check KMP algorithm which can efficiently match word W in a string S.)
If you have a huge amount of substrings to be matched, you then can use split, which costs more space to trade off time.
I think the fastest way should be with
str.indexOf('his name is mike') !== -1
but for 1k words i dont think its relevant
Your question says you "want to check if Result value is equal to one of the sentences" but your code doesn't check for equality. It allows partial matches — for example if Result is i it matches the i in my name is jack..
If you want to match the whole sentences, you could split the sentences into a Set and then checking for matches is a constant time operation. But they'll need to be exact matches, including whitespace.
var a = "my name is jack. your name is sara. her name is joe. his name is mike";
var nameSplit = new Set(a.split(/\.\s+/g))
var Result = "his name is mike";
if (nameSplit.has(Result)) {
console.log("Result is one of the sentences on var a");
}
Result = "his name is";
if (nameSplit.has(Result)) {
console.log("Result is one of the sentences on var a");
} else {
console.log("not in sentences")
}

Showing two .substring in the same alert()

I have an assessment for Java script basics that I have not been able to study for due to unforeseen circumstances so I am now having to catch up in the little time I have.
My assessment states that I must find the substring of the start of each string, which I have managed to do but I am having trouble joining those two processed substrings into the one alert box ( I know these are frowned upon but the assessment states I must use this). I have tried using the + operator but this gives me the error of the second variable being produced twice. I have posted my code below for anyone to have a look.
function userName(){
var name = "Joe";
var surName = "Bloggs";
name = name.substring(0,1);
surName = surName.substring(0,1);
alert(name);
}
function userName(){
var name = "Joe";
var surName = "Bloggs";
name = name.substring(0,1);
surName = surName.substring(0,1);
alert(name + surName );
}
Basically you can concat two variables (strings) using the + operator. The type of htese variables are defined dynamically and the + operator will concat them into a single variable (string), after that you can show the result into a alert.
function userName()
{
var name = "Joe"
var surName = "Bloggs"
name = name.substring(0,1)
surName = surName.substring(0,1)
var result = name + surName;
alert(result);
}
On the other hand, to get only the first char of a string variable in javascript, you can treats it as a array of chars and access the first index, (starting in 0) for sample:
function userName()
{
var name = "Joe"
var surName = "Bloggs"
var result = name[0] + surName[0]; // get only the first char
alert(result);
}
Alternativelly, there a method called string.concat(string) which allows you to concat two strings.
String concatenation This is a very discussed question in many languages and I recommend you to read this thread on stack overflow:
Best way to concatenate strings in JavaScript?
Have you tried
alert(name + ' ' + surname)
This is just joining to strings with the a space ' '

JavaScript: string Manipulation [duplicate]

This question already has answers here:
Split First name and Last name using JavaScript
(26 answers)
Closed 7 years ago.
I am having a hard time chaining some methods together. Can you please provide some assistance?
The end result should = Mickey MOUSE
var name = "MicKEy MOUse";
function nameChanger(oldName) {
var finalName = oldName;
var splitString = name.split(' ');
var fname = splitString.slice(0,1);
var fname_lower = fname.toLowerCase.slice(1,6);
return fname_lower;
};
console.log(nameChanger(name));
Since I am trying to learn the methods in the function I would appreciate assistance on those items. However, if there are more eloquent ways of performing the same action I would appreciate that input as well.
Thank you in advance for your knowledge and direction.
Split the name into two, based on the space character
var splitString = oldName.split(' ');
Convert the entire first string to lowercase and the second string to uppercase.
var fname = splitString[0].toLowerCase();
var lname = splitString[1].toUpperCase();
Now, just create a new String from fname, by changing the first character to upper case, join it with lname and return it, like this
return fname[0].toUpperCase() + fname.substring(1) + " " + lname;
So, your complete function would look like this
function nameChanger(oldName) {
var splitString = oldName.split(' ');
var fname = splitString[0].toLowerCase();
var lname = splitString[1].toUpperCase();
return fname[0].toUpperCase() + fname.substring(1) + " " + lname;
};
Note: You might be wondering, why we are doing this
fname[0].toUpperCase() + fname.substring(1)
to change just the first character of fname. In JavaScript, Strings are immutable objects. Once a String object is created, it can never be changed. So, we are creating a new String object, based on the modified first character of fname and the rest of fname.
var name = "MicKEy MOUse";
function nameChanger(oldName) {
var splitString = name.split(' ');
return splitString[0].charAt(0).toUpperCase()+splitString[0].slice(1).toLowerCase()+' '+splitString[1].toUpperCase();
};
console.log(nameChanger(name));
Expanded code (for Robert Rossmann):
var name = "MicKEy MOUse";
function nameChanger(oldName) {
//Splitting `oldName` to array with words
var splitString = name.split(' ');
//Setting variable which contains first word
var firstWord = splitString[0];
//Setting variable which contains second word
var secondWord = splitString[1];
//Setting variable which contains first letter of first word
var firstWordLetter = firstWord.charAt(0);
//Setting variable which contains first word letters, without first letter
var firstWordRestOfLetters = firstWord.slice(1);
//Result first word (first letter to upper case, rest of letters to lower case)
var resultFirstWord = firstWordLetter.toUpperCase()+firstWordRestOfLetters.toLowerCase();
//Result second word (all second word letters to upper case)
var resultSecondWord = secondWord.toUpperCase();
//Returning string with first and second word separated with space
return resultFirstWord+' '+resultSecondWord;
};

Only extract digits with javascript

I need to extract digits only (at least 2 but not more than 3) from an option text in a drop down list and get that shown in an input field. I've read about regexp (http://www.javascriptkit.com/jsref/regexp.shtml) and thought i had it all figured out. But i just can't seem to get it to work.
<script>
function copyEbc() {
var a = document.getElementById("malt"); // the <select>
var onlydig = /\d{1,3}/ // regexp
var option = a.options[a.selectedIndex].text(onlydig); // regexp on options
var txt = document.getElementById("ebc").value;
txt = txt + option;
document.getElementById("ebc").value = txt;
}
</script>
Example, I only want "4" from a selected option with the text "Pilsner 4 EBC".
Am I completely lost here?
Input much appreciated, cheers
You're trying to call the text value as a function (your JS console has probably complained about this).
Match against the regular expression, instead. match[0] will contain the matched text:
var option = a.options[a.selectedIndex].text.match(onlydig)[0];
to simply extract the number(s) from a string use match:
var numberPattern = /\d+/g;
var foo = 'Pilsner 4 EBC';
var numbers = foo.match(numberPattern);
alert(numbers); // alerts the array of numbers
You need to use the "match" method of the regexp object. AFAIK the "text" method you are using do not exist.

Get string length after append name

If i add a value to a string name i want to get the length of the string not the length of the string name.
var wordlist3 = "ABC";
var xc = 3;
var num_words = ('wordlist' + xc).length;
With the above code i get wordlist3.length as 9 when it should be 3. How do i append a string name so it references the length of the string in wordlist3, without making it a global var?
Im expecting the answer:
num_words = 3
not
num_words = 9
The best way to do this would be to put your word list in arrays.
var wordlist = [];
wordlist[0] = 'ABC';
wordlist[0].length;//3
You can also use the window object to get at it, if it's in the correct scope
window['wordlist' + xc].length;//gives 3
Use this for that:
eval('wordlist' + xc).length;

Categories

Resources