Check if entries are seperated by comma - javascript

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));

Related

split function not working in if statment 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)

Check occurrence of element in string with Regex?

I have strings and some of them may contain : or =
I would like to find all cases, where these symbols occurs, but only once(!).
I wrote this code, which works, but would like to solve with Regex expression
function find(stringToCheck: string): string {
return stringToCheck.includes(':') &&
stringToCheck.split(':').length - 1 === 1
? ':'
: stringToCheck.includes('=') && stringToCheck.split('=').length - 1 === 1
? '='
: '';
}
The string is searched for matches with : or = which are then stored as a RegExp match array. The length of this array then matches how many instances of the string were found.
Where the RexExp objects are created the flag "g" is used to find all matches, rather than just the first one.
function find (stringToTest) {
const a = stringToTest.match(new RegExp(":", "g"));
const b = stringToTest.match(new RegExp("=", "g"));
if (a?.length > 1 || b?.length > 1) return true;
return false;
}
console.log(find("hello:world=")); // false
console.log(find("hello world")); // false
console.log(find("hello world====")); // true
Try this:
function find (stringToCheck)
{
return (/^[^:]*:[^:]*$/.test(stringToCheck) && /^[^=]*=?[^=]*$/.test(stringToCheck))||(/^[^:]*:?[^:]*$/.test(stringToCheck) && /^[^=]*=[^=]*$/.test(stringToCheck));
}
console.log(find("iron:man"));
console.log(find("iron=man"));
console.log(find("iron::man"));
console.log(find("iron==man"));
console.log(find("ironman"));
You could use:
^[^:=]*[:=][^:=]*$
function checkString(str){
return /^[^:=]*[:=][^:=]*$/.test(str);
}
console.log(checkString('Neither'));
console.log(checkString('One equal ='));
console.log(checkString('One colon :'));
console.log(checkString('colon equal :='));
console.log(checkString('Multiple = equal ='));
console.log(checkString('Multiple : colon :'));
console.log(checkString('Multiple = both : col=on :'));

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.

array.length never equals zero and halts the program

When no matches occur for a string, the length of that array does not equal 0 and it is impossible to craft a if else statement to allow for a false when there are no matches.
value is a multi-line input from a single textarea, token in this case is var token = "//num" defined in another function and passed in.
Here is my checking function:
function checkValid(value, token)
{
// Checks to see if value contains the token
var reg = new RegExp(token, "g");
var result = value.match(reg);
if (result.length == 1)
{
return true;
}
return false;
}
If the input text contains more than one instance of the token I get a false return, which is what I want, also a single occurrence of the token will return a true. But zero occurrences of the token will not allow any response. At this point I believe the program is halting but of course codepen gives no indication this is the case.
When no matches occur, match returns null rather than an empty array.
Check that result exists before checking result.length.
function checkValid(value, token)
{
// Checks to see if value contains the token
var reg = new RegExp(token, "g");
var result = value.match(reg);
return result && result.length;
}
.match() returns null if there is no match (see MDN's documentation), it doesn't return an empty array:
> 'aa'.match(new RegExp('a', 'g'))
[ 'a', 'a' ]
> 'a'.match(new RegExp('a', 'g'))
[ 'a' ]
> 'b'.match(new RegExp('a', 'g'))
null
You can then check if the result is null or not:
if (result === null) return false
or in a more compact way:
function checkValid(value, token)
{
var reg = new RegExp(token, "g");
var result = value.match(reg);
return (result !== null && result.length === 1);
}

Categories

Resources