split function not working in if statment Javascript - javascript

var text = "Q!123"; //Setting variable
if(isNaN(text.split('')[text.indexOf("!") + 1]) != true){ //Checking if character after the ! is a number
return true; //Return true if true
}else{
return false; //Return false if false
}
At the if statment where I have text.split(''), im not able to use it whilst grabbing a character from the array

you write this match statement in if to check after '!' is number or not
var text = "Q!123";
let match = text[text.indexOf("!") + 1].match(/[0-9]/)
console.log(match)

Related

Understanding solution of Valid Palindrome in Javascript

This is from LeetCode - Valid Palindrome.
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
while (regex.test(s[start])) {
start++;}
--> can't understand how it works, I understood only that s[start] is alphanumeric characters, it will be false
if (!s[start] || !s[end])
--> What does this mean?
Below is the whole code
var isPalindrome = function(s) {
let regex = /[\W]/;
let start = 0;
let end = s.length - 1;
while (start < end) {
// Moves front runner to next alphanumeric
while (regex.test(s[start])) {
start++;
}
// Moves back runner to next alphanumeric
while (regex.test(s[end])) {
end--;
}
// Above would run until null if there are no alphanumeric characters so return true
if (!s[start] || !s[end]) {
return true;
}
// Check if equal and return false if not
if (s[start].toLowerCase() != s[end].toLowerCase()) {
return false;
}
// If index values match continue the while loop
start++;
end--;
}
return true;
};
Please Advise!
Same as previous solution, plus:
+ removing spaces and symbols, except (A-Z,a-z,0-9)
+ lowercasing
const isPalindrome = function(str) {
const expr = /[\W_]/g;
const lowcaseStr = str.toLowerCase().replace(expr, '');
const reverseStr = lowcaseStr.split('').reverse().join('');
return lowcaseStr === reverseStr
};
This is heavily over-engineered. Why not just use one for loop with 2 counters, one starting at 0 and one at the last index and, while they aren't equal, check if the characters at those indices are the same. Or use built in functions like
function palindrome(str){ return str.split('').reverse().join('') == str}

Validating phone numbers. Null is not an object

I'm doing a challenge on Freecodecamp. I'm having a problem that seems to make no sense to me.
function telephoneCheck(str) {
// if string contains a letter then return false //
var exc = /[a-z\?/]/;
// check str to see if it has anything from the //
// regex and then make it into a string. //
var excJoin = str.match(exc).join('');
// if theres something in the //
// variable(something was found with regex) //
// then return false //
if(excJoin.length > 0) {
return false;
}
// else return true //
if(excJoin === null){return true;}
}
telephoneCheck("2(757)622-7382");
Returning false is fine, however when I just want to say else {return true;} it tells me null is not an object. What's the problem?
http://freecodecamp.com/challenges/validate-us-telephone-numbers
String.prototype.match (in your code: str.match(exc)) returns null if it didn't match the regex, so then the code is equivalent to null.join(''), which is an error.
Instead, check if it's null first:
var excResult = str.match(exc);
if (excResult === null) {
// didn't match, do something
} else {
// did match, do something else
}
You must test for nullity before using the object
str.match(exc) returns null if there are no founds for the given pattern.
So your code should do this:
function telephoneCheck(str) {
// if string contains a letter then return false
var exc = /[a-z\?/]/;
//The match() method retrieves the matches when matching a string against a regular expression.
var excResult= str.match(exc);
//return false if there is a found
if(excResult != null) {
return false;
}
else{
//there is no found cause excResult == null
return true;
}
telephoneCheck("2(757)622-7382");

How to check if a variable is empty in JavaScript?

var characterName = document.getElementById("pilotName").value;
var characterID = 0;
var charSecStatus = 0;
var corpName = " ";
var allianceName = " ";
//callback
makeRequest('https://api.eveonline.com/eve/CharacterID.xml.aspx?names=' + characterName, function() {
if (xmlhttp.status == OK_RESPONSE) {
//read character info
characterID = xmlhttp.responseXML.getElementsByTagName("row")[0].getAttribute("characterID");
makeRequest('https://api.eveonline.com/eve/CharacterInfo.xml.aspx?characterID=' + characterID, function() {
if (xmlhttp.status == OK_RESPONSE) {
//read character info
characterID = xmlhttp.responseXML.getElementsByTagName("characterID")[0].innerHTML;
charSecStatus = xmlhttp.responseXML.getElementsByTagName("securityStatus")[0].innerHTML;
corpName = xmlhttp.responseXML.getElementsByTagName("corporation")[0].innerHTML;
allianceName = (xmlhttp.responseXML.getElementsByTagName("alliance")[0] || {
innerHTML: ""
}).innerHTML;
}
});
}
});
(partial code pictured, no bracketspam pls)
I'm trying to check if the "alliance" variable is empty because certain '"corp" are not in "alliances" and it would be critical error on website if it tried to display an empty variable, so is there a way to check if allianceName is empty after retrieving it from the XML tree and setting it to like "No Alliance" if it IS empty?
Thanks
You are declaring true variables here
var corpName = " ";
var allianceName = " "
In JavaScript, the value of a string with whitespace characters is actually truthy. While the above values do look empty, the reality is they're not. Try it out yourself.
Boolean(" ");
=> true
To set these variables empty, you need to declare them without whitespace characters
var corpName = "";
var allianceName = "";
After you have this, there are two ways to check if the variable is empty
if (!corpName || !corpName.length)
Assuming, you did accidentally include the whitespace character, there are several ways to fix this. We can modify these strings in these cases.
Boolean(" ".trim());
=> false
In the above example, the trim() function is used to remove whitespace characters from a string.
You could also search the string for non-whitespace characters
/\S/.test(" ")
=> false
The \S modifier finds all non whitespace characters.
Alternatively, you could also use the replace function
Boolean(" ".replace(/\s/g, ''));
The global flag g finds all references to the previous regular expression.
If you just want to check whether there's any value in a variable, then try this,
if (str) {
//do something
}
or,
//when undefined
if (typeof str == 'undefined'){
//do something
}
If you need to check specifically for an empty string over null, then, try this.
//when defined, but empty
if ((str.length == 0)||(str== ""))
{
//do something
}
You can try something like this:
Note: If you value is null or undefined, !value?true:false should work. Also value.length is also good approach but should be used in case of string. If value is number, value.length will return 0, i.e. true for empty check.
function isEmpty(value) {
switch (typeof(value)) {
case "string": return (value.length === 0);
case "number":
case "boolean": return false;
case "undefined": return true;
case "object": return !value ? true : false; // handling for null.
default: return !value ? true : false
}
}
var a = " ";
console.log(a, "is empty:", isEmpty(a))
console.log(a, "is empty:", isEmpty(a.trim()))
a = 0;
console.log(a, "is empty:", isEmpty(a))
a = undefined;
console.log(a, "is empty:", isEmpty(a))
a = null;
console.log(a, "is empty:", isEmpty(a))
Also, you can change
allianceName = (xmlhttp.responseXML.getElementsByTagName("alliance")[0] || {
innerHTML: "
}).innerHTML;
to
allianceName = xmlhttp.responseXML.getElementsByTagName("alliance")[0].innerHTML || "";
I believe in JavaScript there's a function called isset() which takes one argument and returns true if it is set to a value and false if it is not.

validating input if starts with "T" or "TP"

I have an input. I need to validate if the value starts with "T" followed by numbers or "TP" followed by numbers
Accepted values: T12345 or TP12345
My JavaScript code
var ip_value = document.getElementById('PROMASTER_NO_FW').value;
var v_first_char = ip_value.substr(0, 1);
var v_second_char = ip_value.substr(1, 1);
if (v_first_char.toUpperCase() !== 'T') {
alert('It must be start with T');
return false;
} else {
if (v_second_char.toUpperCase !== 'P' && isNaN(Number(v_second_char))) {
alert('error2');
return false;
} else {
return true;
}
}
function myFunction() {
var ip_value = document.getElementById('test').value; //'AB12345';
var v_first_char = ip_value.substr(0, 1);
var v_second_char = ip_value.substr(1, 1);
if (v_first_char.toUpperCase() !== 'T') {
document.getElementById("error").innerHTML = 'It must be start with T';
} else if (v_second_char.toUpperCase() !== 'P' && isNaN(Number(v_second_char))) {
document.getElementById("error").innerHTML = 'error2';
} else {
document.getElementById("error").innerHTML = 'no error';
}
}
It will work on blur <br />
<input type="text" id="test" onblur="myFunction()">
<span id="error">No Error</span>
I think your logic is perfect and should work fine, you just need to change:
v_second_char.toUpperCase
to
v_second_char.toUpperCase()
in last if condition
Final code will be
var ip_value = document.getElementById('PROMASTER_NO_FW').value;
var v_first_char = ip_value.substr(0, 1);
var v_second_char = ip_value.substr(1, 1);
if (v_first_char.toUpperCase() !== 'T') {
alert('It must be start with T');
return false;
} else {
if (v_second_char.toUpperCase() !== 'P' && isNaN(Number(v_second_char))) { //change in this line
alert('error2');
return false;
} else {
return true;
}
}
Or for the short line of code you can use the regular expression as shown in above answers.
You can use regular expression to achieve your scenario.
var reg = new RegExp(/^TP?[0-9]+$/)
if((string).match(reg))
return true
else
return false
The condition in the if statement can also be used to retrieve the match string from the original string provided.
Pattern matching against a regular expression would be the best thing to use here. Assuming you are returning true if and only if ip_value is a 'T' or 'TP' followed by at least one number:
var ip_value = document.getElementById('PROMASTER_NO_FW').value;
var pattern = new RegExp(/^TP?\d+$/);
return pattern.test(ip_value);
/^TP?\d+$/ is the regular expression pattern or regex for short - if you're not familiar with regexes, a good starting point in the context of Javascript is the MDN Regular Expressions Guide.

Check if entries are seperated by comma

I have several strings that contain entries separated by a comma, for example:
('ENTRY1', 'ENTRY2','ENTRY3')
As you can see, each entry is separated by a comma, either with or without a following blank.
How can I check with JavaScript if between each entry there is always a comma (with or without a blank).
The string can contain 0 to n entries.
Requirement: A script should return true or false based on the following example:
('ENTRY1', 'ENTRY2','ENTRY3') // return false
('ENTRY1' 'ENTRY2''ENTRY3') // return true
('ENTRY1','ENTRY2''ENTRY3') // return true
false = correct entry
true = false entry
From your example:
('ENTRY1', 'ENTRY2','ENTRY3') // return false
('ENTRY1' 'ENTRY2''ENTRY3') // return true
('ENTRY1','ENTRY2''ENTRY3') // return true
Since entry is enclosed within single quote (' '), you can do
function validate(entries) {
if (entries.replace(/ /g, '').indexOf("''") > -1) {
return true;
} else {
return false;
}
}
//Test case
var entries1 = "('ENTRY1', 'ENTRY2','ENTRY3')";
var entries2 = "('ENTRY1' 'ENTRY2''ENTRY3')";
var entries3 = "('ENTRY1','ENTRY2''ENTRY3')";
document.write(validate(entries1)+","+validate(entries2)+","+validate(entries3));
You could use split like this:
var splitArray = someString.split(',');
for explicitly stating its separated by a ,
If I understand this correctly,
you can use regex for this to make sure there's always a comma between two items if your string is exactly as you mention above
var str = "('ENTRY1', 'ENTRY2','ENTRY3')";
str = str.match(/'([^'])+'/g).join(',');
since you updated your code you can use this code to achieve following
('ENTRY1', 'ENTRY2','ENTRY3') // return false
('ENTRY1' 'ENTRY2''ENTRY3') // return true
('ENTRY1','ENTRY2''ENTRY3') // return true
false = correct entry true = false entry
function isNotOK(str){
var match = str.match(/'[^,i]+'/g);
var len = str.match(/'([^'])+'/g)
if(match && len && match.length === len.length){
return false;
}
return true;
}
var str1 = "('ENTRY1', 'ENTRY2','ENTRY3')";
var str2 = "('ENTRY1' 'ENTRY2''ENTRY3')";
document.write(isNotOK(str1) + ' , ' + isNotOK(str2));

Categories

Resources