Compare and index regex in Javascript array - javascript

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

Related

Validating/checking for values after dashes in a string

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.

JavaScript Regex - test for sets of four non-duplicate characters

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

How can I find if ALL of string2 letters are also contained within string1 somewhere?

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
}

match a string using all the strings in array

Hello, I'm trying to make a simple matching game in javascript.
If the the user inserts the text president goes crazy in any way that contains every strings in word_tmp, then the word_tmp becomes true, and if he misses one string then it becomes false.
word_tmp = ['president', 'goes', 'crazy'];
// string 1 contains the president, goes and crazy at one string
string1 = 'president goes very crazy'; // should output true
// string 2 doesn't contain president so its false.
string2 = 'other people goes crazy'; // should output false
How can I accomplish this?
Try this:
var word_tmp = ['president', 'goes', 'crazy'];
var string1 = 'president goes very crazy';
var isMatch = true;
for(var i = 0; i < word_tmp.length; i++){
if (string1.indexOf(word_tmp[i]) == -1){
isMatch = false;
break;
}
}
return isMatch //will be true in this case
You can do it with simple reduce call:
word_tmp.reduce(function(res, pattern) {
return res && string1.indexOf(pattern) > -1;
}, true);
The same code, wrapped in a function:
var match_all = function(str, arr) {
return arr.reduce(function(res, pattern) {
return res && str.indexOf(pattern) > -1;
}, true);
};
match_all(string1, word_tmp); // true
match_all(string2, word_tmp); // false
But this solution won't work for you if you want to match whole words. I mean, it will accept strings like presidential elections goes crazy, because president is a part of the word presidential. If you want to eliminate such strings as well, you should split your original string first:
var match_all = function(str, arr) {
var parts = str.split(/\s/); // split on whitespaces
return arr.reduce(function(res, pattern) {
return res && parts.indexOf(pattern) > -1;
}, true);
};
match_all('presidential elections goes crazy', word_tmp); // false
In my example I'm splitting original string on whitespaces /\s/. If you allow punctuation marks then it's better to split on non-word characters /\W/.
var word_tmp = ['president', 'goes', 'crazy'];
var str = "president goes very crazy"
var origninaldata = str.split(" ")
var isMatch = false;
for(var i=0;i<word_tmp.length;i++) {
for(var j=0;j<origninaldata.length;j++) {
if(word_tmp[i]==origninaldata[j])
isMatch = true;
}
}

Matching exact string with JavaScript

How can I test if a RegEx matches a string exactly?
var r = /a/;
r.test("a"); // returns true
r.test("ba"); // returns true
testExact(r, "ba"); // should return false
testExact(r, "a"); // should return true
Either modify the pattern beforehand so that it only matches the entire string:
var r = /^a$/
or check afterward whether the pattern matched the whole string:
function matchExact(r, str) {
var match = str.match(r);
return match && str === match[0];
}
Write your regex differently:
var r = /^a$/;
r.test('a'); // true
r.test('ba'); // false
If you do not use any placeholders (as the "exactly" seems to imply), how about string comparison instead?
If you do use placeholders, ^ and $ match the beginning and the end of a string, respectively.
In case anyone receives an error like
Syntax Error: Invalid regular expression
by using the .match() function. You could always go back to the roots:
!!note this code is for matchin an exact string, if you want to search for an exact phrase in a string, you should filter it before hand
console.log("Exact data found: ", hasExactString("?hello", "?hello"))
console.log("Exact data found: ", hasExactString("?hello", "?helloBye"))
function hasExactString(data, searchTerm) {
console.log("search for ", searchTerm, " in ", data);
data = data.toLowerCase(); //if search term should be case insensitive
const searchExpressionLength = searchTerm.length;
const dataInputLength = data.length;
if (dataInputLength != searchExpressionLength) {
return false;
}
else {
//search letter by letter -back to the roots
for (var i = 0; i < searchExpressionLength; i++) {
if (data[i] != searchTerm[i]) {
return false;
}
}
return true;
}
}
...13 years late, but nonetheless^^
var data = {"values": [
{"name":0,"value":0.12791263050161572},
{"name":1,"value":0.13158780927382124}
]};
//JSON to string conversion
var a = JSON.stringify(data);
// replace all name with "x"- global matching
var t = a.replace(/name/g,"x");
// replace exactly the value rather than all values
var d = t.replace(/"value"/g, '"y"');
// String to JSON conversion
var data = JSON.parse(d);
Here's what is (IMO) by far the best solution in one line, per modern javascript standards:
const str1 = 'abc';
const str2 = 'abc';
return (str1 === str2); // true
const str1 = 'abcd';
const str2 = 'abc';
return (str1 === str2); // false
const str1 = 'abc';
const str2 = 'abcd';
return (str1 === str2); // false

Categories