Regex match() fails with 'is not a function' error [duplicate] - javascript

I’m using the match function with a Regular Expression.
The code I’m using is:
if(val.match(/^s+$/) || val == "" )
However, it produces the following error:
"val.match is not function"
What is the problem?

I would say that val is not a string.
I get the
val.match is not function
error for the following
var val=12;
if(val.match(/^s+$/) || val == ""){
document.write("success: " + val);
}
The error goes away if you explicitly convert to a string String(val)
var val=12;
if(String(val).match(/^s+$/) || val == ""){
document.write("success: " + val);
}
And if you do use a string you don't need to do the conversion
var val="sss";
if(val.match(/^s+$/) || val == ""){
document.write("success: " + val);
}

the problem is: val is not string
i can think of two options
1) convert to string: might be a good option if you are sure val has to be string
"Same as above answer"
var val=12;
if(String(val).match(/^s+$/) || val == ""){
document.write("success: " + val);
}
2) skip the line: in my case, it was better to just check the val type and skip if it is not string, because it was not a good idea to run "match" function anyways.
val = 12;
if( val.match) {
if(val.match(/^s+$/) || val == "" ) {
document.write("success: " + val);
}
} else {
document.write("not a string: " + val);
}

NOTE: making this an answer as suggested above from my comment.
Definitely make sure val is defined and a String. Also, I'm guessing it's a typo that you don't have a slash before the 's' in your regex. If that is the case you can replace your if test with "if(val.match(/^\s*$)"

Related

My if else statement is not working as intended - innerHTML remaining the same for all statements

I am trying to find out why my conditional statement is not working as intended. The else part of the statement is not working at all, as it remains the same as for the else if statement. I tried to simplify the statement just having an if/else, but it didn't work. I will really appreciate some help to get to the bottom of this issue.
P.S. In my case if I want to use the null statement I must use it as a string. Another mystery.
Here's my code:
var name = prompt("Could you please tell me your name?");
var newP = document.createElement('p');
newP.setAttribute('id', 'mainP');
document.body.appendChild(newP);
if(name == 'null' || '') {
newP.innerHTML = "I'm just looking for Aname! " + String.fromCodePoint(0x1F612);
}else if(name == 'Aname' || 'aname') {
newP.innerHTML = 'Yes, I finally found Aname! ' + String.fromCodePoint(0x1F60D);
}else {
newP.innerHTML = "I'm just looking for Aname! " + String.fromCodePoint(0x1F612);
}
When comparing a variable to multiple values, you must do so in separate comparisons like the following:
if(name == 'null' || name == ''){
}
Currently, your if statement is evaluating the equivalent to the following statement:
if((name == 'null') || ''){
}
Your else part is not working at all because your not using || operator properly in if condition,
Or operator is used to combine two different logical expressions.
In your case name == 'null' and name == '' are two different logical expressions.
Actually you just if..else that's it. If name is Aname or aname then execute if block otherwise execute else block
if(name == 'Aname' || name == 'aname') {
//^^^^^^^^^^ This was missing
newP.innerHTML = 'Yes, I finally found Aname! ' + String.fromCodePoint(0x1F60D);
}else {
newP.innerHTML = "I'm just looking for Aname! " + String.fromCodePoint(0x1F612);
}
Even you don't need two conditions (It is completely depend on your requirement), convert your name to lower case using toLowerCase() and check for aname, like
//Now this will execute if condition if name is aname, Aname, aName, AName ...
if(name.toLowerCase() == 'aname') {
newP.innerHTML = 'Yes, I finally found Aname! ' + String.fromCodePoint(0x1F60D);
}else {
newP.innerHTML = "I'm just looking for Aname! " + String.fromCodePoint(0x1F612);
}

toLocaleString() not work on input change

I want to add thousand separator for numbers as user is typing in. this is my code :
$('.rls').on('input',function (e) {
$(this).val(parseFloat($(this).val()).toLocaleString());
});
It works correctly but when I enter dot character It doesnt add dot to input .what is the problem?
The parseFloat function is always removing the "." so toLocalString will return the number without the "."
You could check if the last character is a "." and place it back. I also added a check for empty string because otherwise it will give a NaN if you delete all the numbers:
$('.rls').on('input',function (e) {
$this = $(this);
const val = $this.val();
if (val === "") {
return;
}
let end = "";
if (val.charAt(val.length-1) === ".") {
end = ".";
}
$this.val(parseFloat($this.val()).toLocaleString() + end);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="rls" />
Do bear in mind, some locales use "," as the decimal so I'm not sure if your code will break on them. Also, in my case, my locale uses "," as thousands separator and this breaks the parseFloat and removes everything after the "," if I write a number above 999.
I think it would be better to let the user input whatever numbers they want without changing the input box while they are writing in it.
Learn to do it without jquery, what is in js core, and you will often find the solution.
document.querySelector(".rls")[0].oninput = (function(e){
e.value = +e.value.toLocaleString()
})
This is what works for me:
document.querySelector("#number-input").oninput = (function(e) {
var input = document.getElementById('number-input')
input.name = input.value.replaceAll('.', '')
if (input.value == "" || input.value == undefined || isNaN(parseInt(input.name)) == true) {
input.value = 0
input.name = "0"
} else {
input.value = parseInt(input.name).toLocaleString()
}
})
<input type='text' id='number-input'></input>

Javascript, string concatenation without ternary operator

Usually I use this:
myVar = "myString is" + 1 === 1 ? " really true" : " false, I think";
Maybe I need just the true part, let's say:
myVar = "myString is" + 1 === 1 ? " really true" : "";
I don't like this part: : "" because is useless.
Is there a way to use something like the below?
myVar = "myString is" + 1 === 1 && " really true";
It works but there is a problem when is false because it writes "false"!
You could always go with a good old if statement
var myVar = 'myString is';
if (1===1){myVar+=' really true';}
I think that makes it more readable than a one line boolean test
To be pragmatic the best pattern and best way to write this is to rely on a helper:
myVar = "my string is"+myHelper(...myParams);
Then in the helper we'll have a case/switch that is made exactly with this purpose and is really readable.
You can just use ||
myVar = (1 === 1 && "myString is really true") || "";
Wrap the 1 === 1 && " really true" inside parentheses () and add || '' like below (also wrapped in parentheses), or could use template literals to save you some time from typing those +s
let myString = "myString is" + ((1 === 1 && " really true") || '');
let myFalseString = "myString is" + ((1 === 0 && " really true") || '');
let onlyFalse = "myString is" + 1 === 1 && " really true";
let myTL = `myString is ${(1 === 1 && "really true") || ''}`;
console.log('My String:', myString);
console.log('False String:', myFalseString);
console.log('Only false:', onlyFalse);
console.log('My Template Literal:', myTL);
Looks much worse than having the extra : "" though so I would still recommend doing it like that:
myVar = "myString is" + 1 === 1 ? " really true" : "";
another way to achieve something like this could be to use an Array, and concat the values if they are not false. Not that it is any shorter than adding the : '', but as far as i know there is no way to get rid of the : ''
console.log( ["my string is", 1 === 1 && "really true"].filter(Boolean).join(" ") );
console.log( ["my string is", 1 === 2 && "really true"].filter(Boolean).join(" ") );
i would prob stick with the : '' or write a helper function that could look something like this.
function concat(){
let str = "";
for(let s of arguments){
str += s ? s : '';
}
return str;
}
console.log( concat("my string is", 1 === 1 && "really true") );
console.log( concat("my string is", 1 === 2 && "really true") );
Analysing the ternary operator we conclude that it's something like this:
// Example: 1 === 1 ? ' is really true' : ''
if (1 === 1) {
return ' is really true';
} else {
return '';
}
So the solution would be simply to remove the 'else' from the ternary operator, generating a 'binary'. Use a lone IF:
if (1 === 1) {
myVar += 'is really true';
}
The best solution to use the logic operator inline is the ternary operator itself. It's not a problem to have the 'false' part of it as a empty string "". But if you're really annoyed by it you could create a function and use the template literals like this:
function myFunction(evaluation) {
if (evaluation) {
return ' really true';
}
return '';
}
let myVar = `My String is ${myFunction(1 === 1)}`;

If/Else Statement Returning false positives

In my code, I have this if/else statement to deal with a situation in which the numbers and letters both return cont = false. I have tried running just this code, with the same result. Obviously, it should execute the code in the else statement. Does anyone have any ideas?
var input = prompt()
if (input == null || " ") {
//Cont determines whether or not to continue
console.log("cont = false");
var cont = false;
}else{
console.log("cont = true");
var cont = true;
}
Because that code is not how you check one input against two values.
if ( input == null || " " )
should be
if (input==null || input == " ")
input == null || " "
evaluates to (result of your comparison) || " ". Now since " " (a non-empty string) is a truthy value this always evaluates to true.
For order of evaluation -
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
Adding to the other replies which are all correct about the || operator and precedence.
Using == is not a good thing to do in most cases, not least because 0 == null etc - if you're checking if it's actually null or an empty string then something like this is safer:
if (input === null || input.trim() === "") {
...
This checks type as well as content, so won't be able to give false positives. though if input isn't a string it will complain.
Thank's so much! As a summary of all of the answers recieved so far:
The OR operator (||) is comparing input == null to " ", the latter of which always evaluates to true
=== is better than ==
Thanks again for all the help and support!

Basic if/then JS/JQuery - Why does this appear to ignore the IF and execute twice?

I've tried about 2 dozen different variations of this and all roads lead to a result that looks like the IF is being completely ignored. Thoughts?
function checkthebox(name,val){
alert(name + val)
if(val === 'no');{
alert('The value is ' + val +' for ' + name);
$('input[name='+name+']').attr('checked', false).button("refresh");
}
if(val === 'yes');{ alert('The value is ' + val +' for ' + name);
$('input[name='+name+']').attr('checked', true).button("refresh");
}
}
checkthebox('epcf11','yes');
if(val === 'no');{
should be
if(val === 'no') {
You have semicolons before the {
Semicolons mark the end of an instruction, your brackets then just create a new block.
Your if should look like:
if (val==='yes'){
I seen the extra semi's too, I went and tested it out, the conditionals still work even with the ';'
http://writecodeonline.com/javascript/

Categories

Resources