I would like to optimize this code:
if (fd.field('Question_2').value.includes('Name') && fd.field('Question_2').value.includes('Address'))
Instead of typing up the same statement after &&, is it possible to put into one if statement?
Here is an example, the syntax isn't correct but something like this would be much better to type and save space in the JS editor..
if (fd.field('Question_2').value.includes = ['Name', 'Phone/Email Address'])
Many Thanks!
CodePudding user response:
/**
* hasEvery - Check if a string includes all the passed values in array
* @param {String} str The string to search
* @param {Array} arr The array with case-sensitive values to search in string
* @return {Boolean} true if all values in array are found in string
*/
const hasEvery = (str, arr) => arr.every(v => str.includes(v));
const value = "foo Address bar Name baz";
console.log(hasEvery(value, ["Name", "Address"])); // true
console.log(hasEvery(value, ["Name", "Test"])); // false
If you like to can also use rest parameters:
/**
* hasEvery - Check if a string includes all the passed values
* @param {String} str The string to search
* @params {...String} args Values to match
* @return {Boolean} true if all values are found in string
*/
const hasEvery = (str, ...args) => args.every(v => str.includes(v));
const value = "foo Address bar Name baz";
console.log(hasEvery(value, "Name", "Address")); // true
console.log(hasEvery(value, "Name", "Test")); // false
CodePudding user response:
The first thing you could do is just use a variable instead of looking it up
const q2Value = fd.field('Question_2').value.
if (q2Value.includes('Name') && q2Value.includes('Address')){}
Other option is using reg exp using look aheads
const namAddyRegExp = /^(?=.*\bName\b)(?=.*\bAddress\b).*$/;
const str = "sfdsafdsf Name sdafdsf dsfdsf Address sdfsaf";
if(namAddyRegExp.test(str)){}
CodePudding user response:
EDIT: Using regex:
fd.field('Question_2').value.match(/(?=.*Name)(?=.*Address)/);
As long as you have only few strings to compare like Name
and Address
, it should be acceptable.
old post:
wrong solution, checking if only one of the string is in the value:
fd.field('Question_2').value.match(/(Name|Address)/);