I really need your help,
I’d like to make a function so as to validate (return valid or invalid) that the following string below (represented by the var x) has values after each of the 7 dashes
var x = 4-D-5240-P43-120-08A2-8123-0000 (valid)
Some examples below of strings where x is invalid)
var x = 4--5220--120-08C2-8072- (invalid)
var x = 4--5217-P41-120--8072- (invalid)
var x = --5217-P41---8072- (invalid)
I've tried the following, but errors when there is no value:
function test() {
var str1 = "4-D-5240-P43-120-08A2-8123-0000" //works
str1 = str.split('-')
var str = "4--5240-P43--08A2-8123-0000" //error here <--
str = str.split('-')
if (str.length < 8) { alert('validation failed') }
else { alert('validation passed!') }
}
Have you considered Regex?
const
pattern = /(([\d\w]+)-([\d\w]+)-([\d\w]+)-([\d\w]+)-([\d\w]+)-([\d\w]+)-([\d\w]+)-([\d\w]+))/,
strs = ["4-D-5240-P43-120-08A2-8123-0000", "4--5217-P41-120--8072-", "--5217-P41---8072-", "4--5220--120-08C2-8072-"];
strs.forEach((str) => {
console.log(`${str} is valid: ${ pattern.test(str) }`);
});
You can try something like this using regex.
var regex1 = /[0-9|a-z][-][0-9|a-z]/g;
var str = "4--5220--120-08C2-8072-";
var str1 = "4-D-5240-P43-120-08A2-8123-0000"
if(str.match(regex1).length== 4) {
alert("match");
}
else
{
alert("no match");
}
if(str1.match(regex1).length== 4) {
alert("match");
}
else
{
alert("no match");
}
So for 1st declared the code and data-target "-"
var id= "100-2-8-8-8-8-8ssss80-0";
var arr = id.split("-");
1st step of checking if code is valid or no. Of we will have less or more than 7 dashes output will be invalid otherwise function will run anouther function to check if we have dashes in right place.
function countDash(){
if (arr.length ==8){
result();
}
else{
alert("invalid");
}
}
After we split our function we need to check if every value of array have a value. If dash will be 1st,last or multicharacter we will get empty value.
function check(value){
return value.length<1;
}
Now we use function that we declarete before to check every value of array. So if array will be empty we will have output invalid otherwise code will be valid
function result(){
if(arr.some(check)){
alert("invalid");
}
else{
alert("valid");
}
}
Finally we need to run 1st function.
window.onload= countDash ;
I hope I explain you well how it goes. If there is something else to do just let me know.
Related
I am trying to use Regex to test if a certain string contains only sets of four non-duplicate characters.
For example I would like to test string
acbdbcaddacb
which would return true as it can return
acbd
bcad
dacb
i.e. sets of four characters which have no duplicates even though the entire string does.
I have tried the following regex which does not work for example and I am not sure why:
/^(?:(?:([a-d])(?!.{0,2}\1))(?:([a-d])(?!.{0,1}\1))(?:([a-d])(?!\1))[a-d])+$/
Any solutions?
Thank you
You're close. Your current regex is only checking if the 2nd - 4th letters in each group match the 1st. I believe /^(?:(?:([a-d])(?!.{0,2}\1))(?:([a-d])(?!.{0,1}\1|\2))(?:([a-d])(?!\1|\2|\3))[a-d])+$/ should work... or at least it's getting closer to correct I'm not sure if I left out some edge cases but it seems to be working for my test strings
Try this :
function check(str) {
var len = str.length; // check string length
if (len % 4 == 0) { // pass if divided by 4 == true
var arr = str.match(/.{4}/g); // make the in array
var res = [];
for (i = 0; i < arr.length; i++) {
if (arr[i].match(/^(?:([a-zA-Z])(?!.*\1))*$/)) {
res.push(arr[i]); // push if passed regex
}
}
if (arr.length === res.length) { // if they same that means true
console.log("true");
} else {
console.log("false");
}
} else {
console.log("false");
}
}
var str1 = "acbdbcaddacb";
check(str1); // true
var str2 = "aabbccdd";
check(str2); // false
var str3 = "abcde";
check(str3); // false
var str4 = "abcdabcdabcdabcd";
check(str4); // true
var str5 = "abcdabcdabcdabc4";
check(str5); // false
I have two arrays:
enteredCommands = ["valid", "this", 1.1];
validParameters = [/valid/, /alsoValid/, /this|that/, /\d+(\.)?\d*/];
I want to loop through all of the enteredCommands, if it exists in validParameters remove it from validParameters, if it doesn't, break.
I don't know how to compare the regex in this way, if I change validParameters to:
validParameters = ["valid", "alsoValid", /this|that/, /\d+(\.)?\d*/];
and use:
var ok2go = true;
// For each entered command...
for (var i = 0; i < commands.length; i++) {
// Check to see that it is a valid parameter
if (validParameters.indexOf(commands[i]) === -1) {
// If not, an invalid command was entered.
ok2go = false;
break;
// If valid, remove from list of valid parameters so as to prevent duplicates.
} else {
validParameters.splice(validParameters.indexOf(commands[i]), 1);
}
return ok2go;
}
if (ok2go) {
// do stuff if all the commands are valid
} else {
alert("Invalid command");
}
It works the way I want it to for the strings, but obviously not for those values that need to be regex. Is there any way to solve this?
Test cases:
enteredCommands = ["valid", "this", 1.1, 3];
// Expected Result: ok2go = false because 2 digits were entered
enteredCommands = ["valid", "alsoValid", "x"];
// Expected Result: ok2go = false because x was entered
enteredCommands = ["valid", "alsoValid", 1];
// Expected Result: ok2go = true because no invalid commands were found so we can continue on with the rest of the code
You could filter the given commands and if a regular expression match, the exclude it from the regex array. Return only commants which does not match with the rest of the regex array.
function check(array) {
var regex = [/valid/, /alsoValid/, /this|that/, /\d+(\.)?\d*/];
return array.filter(function (a) {
var invalid = true;
regex = regex.filter(function (r) {
if (!r.test(a)) {
return true;
}
invalid = false;
});
invalid && alert('invalid command: ' + a);
return invalid;
});
}
console.log(check(["valid", "this", 1.1, 3])); // 2 digits were entered
console.log(check(["valid", "alsoValid", "x"])); // x was entered
console.log(check(["valid", "alsoValid", 1])); // nothing, no invalid commands were found
I recommend you split up the checks for a matching regex and the check for a matching string.
Conceptually, you might want to do the following (code not tested)
var validStringParameters = ["valid", "alsoValid"];
var validRegexMatches = [/valid/, /alsoValid/, /this|that/, /\d+(\.)?\d*/];
var validCommands = enteredcommands.filter(function(command){
if (validStringParameters.indexOf(command) !== -1){
return true;
}
for (var i = 0; i < validRegexMatches.length; i++){
if (command.test(validRegexMatches[i]){
return true;
})
return false;
}
})
I am trying to compare two strings to see if ALL of one of the string's input is also within another string, regardless of order.
So far I have the following code...
What am I doing wrong?
var str1= "rkqodlw"
var str2= "world"
StringScrambler(str1, str2);
function StringScrambler(str1, str2) {
var string1= str1.split("").sort();
console.log(string1);
var string2 = str2.split("").sort();
console.log(string2);
matches = [];
for (i=0; i< string1.length; i++) {
for (j=0; j<string2.length; i++) {
while (j === i) {
matches.push(j);
console.log(matches);
var matchSort = matches.sort();
console.log(matchSort);
if (matchSort === string2) {
return true;
}else {
return false;
}
}
}
}
}
All the answers this far work fine but they will not work for words with double letters in the second string but not in the first (for eg. 'worlld' - notice the double L). The trick is to affect the first word such that it removes the found character(s) so that the same letter is not checked again. Something like this would do the trick:
// Check if the second string's characters are
// found in the first string
function StringScrambler(str1, str2) {
var arr1 = str1.split(''),
arr2 = str2.split(''),
isATrueSubset = true,
indexOfChar;
arr2.forEach(function(char) {
indexOfChar = arr1.indexOf(char);
if (indexOfChar > -1) {
// Remove the character that was found
// to avoid matching against it again
arr1.splice(indexOfChar, 1);
} else {
isATrueSubset = false;
// No need to continue
return;
}
});
console.log(isATrueSubset);
return isATrueSubset;
}
StringScrambler('rkqodlw ', 'world '); // outputs true
StringScrambler('rkqodlw ', 'worlld '); // outputs false
var one = "dlrow";
var two = "world";
var allCharsFound = true;
one.split("").map(function(char) {
if (two.indexOf(char) < 0) {
allCharsFound = false;
}
});
console.log(allCharsFound);
var str1= "rkqodlw";
var str2= "world";
function test($str1, $str2) {
var string2 = str2.split("");
for(var i=0; i<string2.length; i++) {
if (str1.indexOf(string2[i]) == -1) {
return false;
}
}
return true;
}
You can use the following code to do this task:
alert (AllFirstInSecond("world", "rkqodlw"));
alert (AllFirstInSecond("worldz", "rkqodlw"));
function AllFirstInSecond(str1, str2) {
var pos = str1.length - 1;
while (pos >= 0) {
if (str2.indexOf(str1.substr(pos--,1)) == -1) {
return false;
}
}
return true;
}
It simply checks every single character in the first string to see if it's in the second. If not, it returns false.
Only once all have been found does it return true.
There are possibilities for optimisation (every character is checked even if it's a duplicate that's already been checked) but, unless your strings are particularly large, there's probably not much absolute gain to be had.
If str2 is always a subset of str1, then this answer can be used
Compute intersection of two arrays in JavaScript
var arr1 = "rkqodlw".split("");
var arr2 = "world".split("");
var commonValues = arr2.filter(function(value) {
return arr1.indexOf(value) > -1;
});
alert(commonValues.join(""))
This will compare each words of the second string in the first one and if its present it will be added in the mathes array.
var str1= "rkqodlw";
var str2= "world2";
StringScrambler(str1, str2);
function StringScrambler(str1, str2) {
var string2 = str2.split("").sort();
console.log(string2);
matches = [];
for (j=0; j<string2.length; j++) {
if(str1.indexOf(string2[j]) > -1){
matches.push(string2[j]);
console.log(string2[j]);
}
}
console.log(matches);
}
try this:
var str1= "rkqodlw"
var str2= "world"
StringScrambler(str1, str2);
function StringScrambler(str1, str2) {
var string1 = str1.split("").sort();
var string2 = str2.split("").sort();
matches = [];
for (i = 0; i < string1.length; i++) {
if (string2.indexOf(string1[i]) > -1) matches.push(string1[i]);
}
return matches
}
I am trying to validate a string only if its first 5 characters are numeric and last 5 characters are letters:
What I have tried:
var userId = "12345abcde";
// Get First and Second Five Characters
var firstFive = userId.substring(0, 5);
var secondFive = userId.substring(5, 10);
// get Global Letter and Nummers
var aStr = /[a-z, A-Z]/g;
var aNum = /[0-9]/g;
var c = userId.match(aNum);
// Try firstFive first...
if (firstFive === c) {
alert('yes');
} else {
alert('nop');
}
This alerts nop.
Is this because firstFive is string and c is object? Where is the error in my thinking?
Live example: http://jsfiddle.net/xe71dd59/1/
Any tips?
Thanks in advance!
Try
/^[0-9]{5}.*[a-z]{5}$/i.test("12345abcde")
match returns an array of results or NULL if none were found.
var c = firstFive.match(aNum);
if(c!=null)
{
if(c.length==5)
{
alert("Yes");
}
}
Try to do this way:
var userId = "12345abcde";
var result = /^[0-9]{5}.*[a-z]{5}$/i.test(userId);
if (result) {
alert('yes');
}else{
alert('nop');
}
I have an expression say
log(1,3)+4,5+max(7,8,9)
where comma is being used two ways.
1- In "log(1,3)+4,5" comma is being used in place of dot(.) or decimal sign.i.e. "log(1,3)+4,5" is equivalent to "log(1.3)+4.5".
2- In max(7,8,9) it is being used as number separator. i.e. this outcome of this is 9 ; the maximum number.
My problem is to substitute comma; which is being used as decimal separator; with decimal but this should not affect max(7,8,9). i.e. I need to convert above expression to
log(1.3)+4.5+max(7,8,9)
What I tried-
function substitute(expr) {
expr.replace(/,/g, function ($`) {
/*some processing here to decide whether comma to be substituted with dot or not.On that basis I will return either dot or comma.*/
}
But how can I pass $` value to associated function
or
Is it possible to do this in javascript.
expr.replace(/,/g,function ($`) {
if yes then how?
Your language is ambiguous.
max(8,1,8,2)
Does this return 8, 8,1 or 8,2?
Your language also doesn't look regular, so you can't parse it with a regular expression, you need the context. If something like this is allowed:
max(1,max(2,3)) // 3?
Assuming you can get rid of the ambiguity, you could write a parser to do the context detection.
This could be a solution :
function myFilter(string) {
// save all functions and signs
var functions = [];
var regExp = /[+,-]max\(([^\)]+)\)/;
matches = true;
while (matches !== null) {
var matches = regExp.exec(string);
if (matches !== null) {
functions.push(matches[0]);
string = string.replace(matches[0], '');
}
}
// replace all remaining commas with dots
string = string.replace(/,/g , ".");
for (i in functions) {
string += functions[i];
}
return string;
}
var s = '1,3+4,5+max(7,8,9)-max(2,3,5)';
var filteredString = myFilter(s);
jsFiddle Demo
This currently works with multiple max functions but only + and - signs. It could be improved with *, / and more... You will have to find the good regex.
Try the below using Javascript. Hope this helps you in logic.
DEMO HERE
var value = "log(1,3)-4,5+max(7,8,9)";
var val = '';
var splitValue, appendSym;
if (value.indexOf("+") != -1)
{
splitValue = value.split("+");
appendSym = "+";
}
else if(value.indexOf("-") != -1)
{
splitValue = value.split("-");
appendSym = "-";
}
else if(value.indexOf("*") != -1)
{
splitValue = value.split("*");
appendSym = "*";
}
else
{
splitValue = value.split("/");
appendSym = "/";
}
var length = splitValue.length;
for (var i = 0; i < length; i++) {
if (val) val += appendSym;
var strrep = splitValue[i].replace(/,/g,".");
if (splitValue[i].indexOf("max") != -1 || splitValue[i].indexOf("min") != -1)
{
val+=splitValue[i];
}
else
{
val+=strrep;
}
}
alert(val);
The output for the above code is log(1.3)-4.5+max(7,8,9)