I am trying to simplify the following codes. The codes seem to redundant to me. Are there anyone here can help me out? Thanks a lot!
if(area.regionCode=='0' || area.regionCode==null){
var fakecode=area.region.substring(0, area.region.length - 1);
area.region= fakecode +i;
}
Whenever you think some code is not directly revealing, try giving it a new home with a suitable name:
if (!isValidRegionCode(area.regionCode)) {
...
}
...
function isValidRegionCode(regionCode) {
return area.regionCode != null && area.regionCode != '0';
}
It has more code overall, but makes your intentions clear.
if(parseInt(area.regionCode) > 0) {}
I would recommend explicit condition checks. When using:
if (area.regionCode) { }
Style of logic, one is treating varAny as a boolean value. Therefore, JavaScript will perform an implicit conversion to a boolean value of whatever object type varAny is.
or
if(Boolean(area.regionCode)){
codes here;
}
both will work same
returns false for the following,
null
undefined
0
""
false.
beware returns true for string zero "0" and whitespace " ".
you can also first trim the output so " " issue will be solve
here tutorial How do I trim a string in javascript?
in the #mttrb and #nnnnnn described case you can first convert string to either int or float by parseInt() and parseFloat() check this Converting strings to numbers
Related
I'm having difficulties figuring out why the code below doesn't work as expected:
const userInput = prompt("Enter something");
if (userInput) {
console.log("TRUTHY");
} else {
console.log("FALSY");
}
I keep getting "TRUTHY" no matter what I do. I understand the logic of this code and even when running the source file from the class I'm not getting the expected output.
I should get "FALSY" whenever the input is: 0, null, undefined, an empty string or NaN.
What am I doing wrong?
Thank you.
Edit 1: Turns out I was getting ahead of myself. The code should in fact return "TRUTHY" unless you input an empty string.
Which browser are you using? because when I run this code on ms edge, it returns FALSY when I enter nothing. Also, userInput is set to a string type by default, and the string "0" is true as it contains something. You'll have to use parseInt() to convert the value to an integer, though that doesn't look like what you want to do. Consider looking for syntax errors, and check if your browser is up to date.
Since userInput is a string we have to check its length to find out whether it is empty
const userInput = prompt("Enter something");
if (userInput.length !== 0 && userInput == 0 && userInput == null && userInput == NaN) {
console.log("TRUTHY");
} else {
console.log("FALSY");
}
Change that if() to:
if (userInput == true) {
It's because the if(), as you have it, does a strict equality (===), so object types much match.
How can I make a function that takes a string and checks if it is a number string or if it includes letters/other characters? I have no idea what to do... RegExp takes too long so is there another way?
You have to use isNaN() function (is Not a Number). It will return you true if it's not a number (that mean that it contains letter) and false if it's one.
Source :
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/isNaN
You can check for isNaN and see if value is number if you don't want to go with RegExp.
let inpArgs = Number.parseInt(input);
if(!Number.isNaN(inpArgs)){
// this check ensures that your input is number
// Do what you have to do
}
else{
// Handle the error
}
But I would prefer the one line check using RegExp any day like below.
if(/^\d+$/.test(Number(input))){
// this says your input is Number
}
You can use typeof oprator to check whether it is a number or string.
function(anything){
if(typeof(anything)==='number'){ //do something} }
if(typeof(anything)==='string'){ //do something} }
Hope I answer your question.
Thanks.
You can use typeof in JavaScript to identify input Like
alert(typeof <your input>); or var identity = typeof <your input>;
and whatever string alert that match in Condition Like
if (identity == <alert message>){do something}else{do something}
I am trying to compare the variable using javascipt:
response value: ""test#gmail.com""
response value i am getting it from server.
var str1="test#gmail.com"
var str2 =response;
if(str1===str2)
{
//
}
However not getting the proper result.
any idea on how to compare them ?
There are a few ways to achieve your goal:
1) You can remove all " from the response when doing your equality check:
if(str1===str2.replace(/['"]+/g, ''))
{
//
}
2) Change your server code to not include ". Doing so, would mean that your Javascript will not need to change.
3) Last option, add " to your str1:
var str1='"test#gmail.com"'
var str2 =response;
if(str1===str2)
{
//
}
Obviously I don't know enough about your requirements to tell you which one you should do, but my suggestion would be choice #2 because I think it's strange to return an email address wrapped in quotes, otherwise I would recommend #1.
You are trying to compare '""test#gmail.com""' with 'test#gmail.com'. They would never be equal.
Actually ""test#gmail.com"" is not a valid string. It might have been represented as '""test#gmail.com""' and "test#gmail.com" is a valid string (Same as 'test#gmail.com').
I was in an interview the other day and I was asked to write a method that reverses a string recursively.
I started writing a method that calls itself and got stuck.
Here is what I was asked, reverse a string "Obama" recursively in JavaScript.
Here is how far I got.
function reverseString(strToReverse)
{
reverseString(strToReverse);
};
And got stuck, they said NO for i loops.
Anyone got any ideas?
Look at it this way: the reversed string will start with the last letter of the original, followed by all but the last letter, reversed.
So:
function reverseString(strToReverse)
{
if (strToReverse.length <= 1)
return strToReverse;
// last char +
// 0 .. second-last-char, reversed
return strToReverse[strToReverse.length - 1] +
reverseString( strToReverse.substring(0, strToReverse.length - 1) );
}
See the solution by #MaxZoom below for a more concise version.
Note that the tail-recursive style in my own answer provides no advantage over the plain-recursive version since JS interpreters are not required to perform tail call elimination.
[Original]
Here's a tail recursive version that works by removing a character from the front of the input string and prepending it to the front of the "accumulator" string:
function reverse(s, acc) {
if (s.length <= 0) { return acc; }
return reverse(s.slice(1), s.charAt(0) + (acc||''));
}
reverse('foobar'); // => "raboof"
The simplest one:
function reverse(input) {
if (input == null || input.length < 2) return input;
return reverse(input.substring(1)) + input.charAt(0);
}
console.log(reverse('Barack Obama'));
Single line solution. And if they asked I tell them it's recursive in the native code part and not to ask any more stupid questions.
var result = "Obama".split('').reverse().join('');
Output: amabO
The real problem here is not "how to reverse a string". The real problem is, "do you understand recursion". That is what the interview question is about!
So, in order to solve the problem, you need to show you know what recursion is about, not that you can reverse the string "Obama". If all you needed to do was reverse the string "Obama", you could write return "amabO"; see?
In other words, this specific programming task is not what it's all about! The real solution is not to copy and paste the code from the answers here, but to know about recursion.
In brief,
Recursion involves calling the same function again, yes, but that's not all
In order to prevent stack overflow, you MUST ensure that the function doesn't call itself indefinitely
So there's always a condition under which the function can exit without calling itself (again)
And when it does call itself again, it should do so with parameters that make the above condition more likely.
In the case of string operations, one way to make that all happen is to make sure that it calls itself only with strings that are shorter than the one it was called with. Since strings are not of an infinite length, the function can't call itself an infinite number of times that way. So the condition can be that the string has a length of zero, in which case it's impossible to call itself with a shorter string.
If you can prove that you know all this, and can use it in a real world program, then you're on your way to passing the interview. Not if you copy and paste some source you found on the internet.
Hope this helps!
We can easily reverse a string in the recursion method using the ternary operator
function reverseString(strToReverse) {
return str.length > 1 ? reverse(str.slice(1)) + str.charAt(0) : str;
}
reverseString("America");
Not the smartest way to reverse a string, but it is recursive:
function reverse(input, output) {
output = output || '';
if (input.length > 0) {
output = output.concat(input[input.length -1]);
return reverse(input.substr(0, input.length - 1), output);
}
return output;
}
console.log(reverse('Obama'));
Here's a jsfiddle
Maybe something like this?
var base = 'Obama',
index = base.length,
result = '';
function recursive(){
if (index == 0) return;
index -= 1;
result += base[index];
recursive();
}
recursive();
alert(result);
jsfiddle:
https://jsfiddle.net/hy1d84jL/
EDIT: You can think of recursion as an infinite for..loop. Let's just use it in "controlled" way and define the bounds - 0 for minimum and the length of Obama word as the maximum. Now, let's just make it call itself whatever number of times and do what you need in order to reverse the string, which is - decrement the index variable by one and sum the character from the end. Hope it helps. Nice question.
If the function can only have the single input i would split the string into smaller and smaller pieces, and add them all together in the reverse order
function reverseString(strToReverse){
if (strToReverse.length <= 1) { return strToReverse; }
return reverseString(strToReverse.substr(1, strToReverse.length - 1) + strToReverse[0];
}
if(kword == term){
$(this).trigger('click');
}
The case is if the kword is "car" and the term is "cars", I would want that to be a positive match.
Currently I'm looking at an exact match. As I'm a novice at jquery I don't know how to do this. Can anyone point me to the right direction?
You can use indexOf() to find the string inside another
if(term.indexOf(kword)>-1){
//code
}
If you need to simply compare a string variable with a different string variable with an 's' in the end, you can go with following code:
if (term === kword + 's') {
...
}
If you need to check specifically if terms is a plural version of kword, you would need much larger implementation, featuring pluralize function (that you need to implement or search for a library):
if (term === pluralize(kword)) {
...
}
function pluralize(word) {
//implement function
}
If that doesn't not answer your question, please be more clear about what you need to do.
As #Anton said, you can use indexOf(), it returns the position of the first occurrence of a specified value in a string otherwise returns -1 if the value to search for never occurs. Also note that this method is case sensitive.