Javascript in list - javascript

What's the easiest way to check to see if a number is in a comma delimited list?
console.log(provider[cardType]);
//returns: Object { name="visa", validLength="16,13", prefixRegExp=}
if (ccLength == 0 || (cardType > 0 && ccLength < provider[cardType].validLength)) {
triggerNotification('x', 'Your credit card number isn\'t long enough');
return false;
} else {
if ($('.credit-card input[name="cc_cvv"]').val().length < 3) {
triggerNotification('x', 'You must provide a CCV');
return false;
}

Seems similar to this SO question.
Just .split() the CSV and use inArray.

Not sure how your sample code relates to checking to see if a number is in a comma delimited list...
Also not sure if this is the easiest way, but it's what springs to mind:
<script type="text/javascript">
var myNumbers = "1,2,3,4,5";
var myArray = myNumbers.split( ',' );
// looking for "4"
for ( var i=0; i<myArray.length; i++ ) {
if (myArray[i] == 4) {
alert('Found it!');
break;
}
}

I do not see where you have a significant comma delimited list in the script you posted.
The fastest way could be something like
var csvList ="a,b,c,d,e,f,g,h";
var testList = ","+csvList+",";
var needle = "f";
alert(testList.indexOf(","+needle+",")!=-1)
just to be different ;)

If it's just a list of comma separated numbers with nothing fancy, you can just use the split method:
var numbers = list.split(",");
This will give you an array of all of the numbers in the list. Checking whether a number is in an array is trivial.

Native JavaScript and therefore cross-browser compliant. Some frameworks provide functions that do this for you, but you don't get more basic than the following.
var numbers = list.split(",");
var count = numbers.length;
var exists = false;
for (var i = 0; i < count; ++i) {
if (numbers[i] == anumber) {
exists = true;
break;
}
}

From your sample, I assume your question was "How do I see if a number is within a range of two values specified by a single-comma-delimited string?":
function inRange( number, stringRange ){
var minmax = stringRange.split(',');
minmax[0] = minmax[0]*1; //convert to number
minmax[1] = minmax[1]*1; //convert to number
minmax.sort(); // Ensure [0] is the min
return number>=minmax[0] && number<=minmax[1];
}

Try this one...
console.log(provider[cardType]); //returns: Object { name="visa", validLength="16,13", prefixRegExp=}
var regExp = new RegExp(",?" + ccLength + ",?");
if (ccLength == 0 || (cardType > 0 && !regExp.test(provider[cardType].validLength)))
{
triggerNotification('x', 'Your credit card number isn\'t long enough');
return false;
}
else
{
if ($('.credit-card input[name="cc_cvv"]').val().length < 3)
{
triggerNotification('x', 'You must provide a CCV');
return false;
}
}

Related

Regular Expression to check- No more than 2 sequential numbers or characters and No more than 1 same numbers or characters-Javascript

I want to reject user input if it contains 2 sequential numbers or characters ,for example 1234,jkl, zyxw and if it contains more than 1 same numbers or characters like aaer,0000,aabb,pp22. Thank you for insights. I have regex for the second one but dont know how to combine the two expressions:
"([a-zA-Z0-9])\\1{1,}"
Doing this in regex is neither sound nor practical. However, you can easily check if your input contains a sequential (abc.. or cba) pattern using code like that:
function isSequencial(input) {
var numpattern = '0123456789012345789'; // match ascending/descending sequence of numbers.
var charpattern = 'ABCDEFGHIJKLMNOPQRSTUVWXYZYXWVUTSRQPONMLKJIHGFEDCBA'; // match ascending/descending sequence of letters.
for (var i = 0; i < input.length-1; i++) {
var shard = input.substring(i,i+2);
if(numpattern.indexOf(shard) != -1) {
console.log('sequential number pattern detected: ' + shard);
return true;
}
if (charpattern.indexOf(shard.toUpperCase()) != -1) {
console.log('sequential letter pattern detected: ' +shard);
return true;
}
}
return false;
}
console.log("isSequencial(a234):" + isSequencial("a234"));
console.log("isSequencial(azyx):" + isSequencial("azyx"));
console.log("isSequencial(xbc):" + isSequencial("xbc"));
console.log("isSequencial(2435):" + isSequencial("2435"));
This code can be optimized but is easy to understand and maintain since it does not try to do multiple things at once. You should be able to combine this with your existing approach.
The simplest solution for your first requirement would be to parse it, as with a regex it will be not that easy to set up, if at all possible.
Here I used charCodeAt (and check for both sequence/equal and duplicates characters)
var input1 = "1543abc3";
var input2 = "cba23DEf";
var input3 = "ba2354cd";
console.log('test 1');
testit(input1.split(''));
console.log('test 2');
testit(input2.split(''));
console.log('test 3');
testit(input3.split(''));
function testit (arr) {
var prev = arr[0].charCodeAt(0) + 1, prev2 = -1;
for (var i = 1; i < arr.length; i++) {
var arritem = arr[i].charCodeAt(0);
if ( (arritem == prev && arritem == (prev2+1)) || // abc
(arritem == (prev-2) && arritem == (prev2-3)) // cba
) {
console.log(' - sequence, more than 2: ', arr[i-2], arr[i-1], arr[i] );
//return false;
}
if (arr.indexOf(arr[i-1],i) > -1) {
console.log(' - duplicate, more than 1: ', arr[i-1] );
//return false;
}
prev2 = prev;
prev = arr[i].charCodeAt(0) + 1;
}
//return true;
}

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 compare two shuffled strings?

I have the following two strings:
var str1 = "hello";
var str2 = "ehlol";
How can I check whether both strings contain the same characters?
May not be very optimal, but you can simply do
str1.split("").sort().join() == str2.split("").sort().join(); //outputs true
Another suggested approach in one the comments (for optimization in case string length is quite big)
str1.length===str2.length && str1.split("").sort().join() == str2.split("").sort().join(); //first check the length to quickly rule out in case of obvious non-matches
One of the recommended ways to do it is using a hash table: count how many times each character appears. Note that this works best if your characters are ASCII.
The complexity of this algorithm is O(M+N+sigma) where M, N are the lengths of the strings and sigma is the number of distinct letters. The complexity of the accepted solution is higher because of the sorting, which is usually done in O(N*logN), but still a good one if your strings are short. If your strings have hundreds of thousands of characters, then this is the way to go. The drawback of using hash tables is that the memory usage is higher than the solution that uses sorting.
function sameLetters(str1, str2){
var hash = {};
var len1 = str1.length;
var len2 = str2.length;
// Strings with different lengths can't contain the same letters
if(len1 !== len2) return false;
// Count how many times each character appears in str1
for(var i = 0; i < len1; ++i) {
var c = str1[i];
if(typeof hash[c] !== 'undefined') hash[c]++;
else hash[c] = 1;
}
// Make sure each character appearing in str2 was found in str1
for(var i = 0; i < len2; ++i) {
var c = str2[i];
if(typeof hash[c] === 'undefined') return false;
if(hash[c] === 0) return false;
hash[c]--;
}
// Make sure no letters are left
for(var c in hash) {
if(hash[c]) return false;
}
return true;
}
You can then call the function like this (play with it in the browser console):
sameLetters("hello", "ehlol"); // true
sameLetters("hello", "ehllol"); // false
You can use a function for this purpose like sameChars function here-
function myFunction()
{
var input_1 = document.getElementById('input_1').value;
var input_2 = document.getElementById('input_2').value;
var result = sameChars(input_1,input_2);
document.getElementById("demo").innerHTML = result;
}
function sameChars(firstStr, secondStr)
{
var first = firstStr.split('').sort().join('');
var second = secondStr.split('').sort().join('');
return first.localeCompare(second)==0;
}
<input type="text" maxlength="512" id="input_1"/>
<input type="text" maxlength="512" id="input_2"/>
<button onclick="myFunction()">Check If Shuffled</button>
<p id="demo"></p>
Here's a modified version of Gurvinders answer.
var str1 = "hello",
str2 = "ehlol";
// Add sort on prototype of String object
String.prototype.sort = function () {
return this.split('').sort().join('');
};
// First check if length of both is same
var same = str1.length === str2.length && str1.sort() === str2.sort();
console.log('Strings are same?', same);
You could possibly say this:
(a.length === b.length) && (a.split('').every(function(val) { return b.indexOf(val) > -1}))
And, in ES6 you could make it look as follows:
(a.length === b.length) && a.split('').every(val => { return b.indexOf(val) > -1 })

comma separated string javascript

I'm sorry it's a stupid question but I'm try to list a sequence of numbers from 1 to a limit and they should be separated by comma. I have a problem. I don't know how to stop the comma. I should have 1,2,3 but I have ,1,2,3. Can you help me? Here is my code.
function getNumberSequence(number) {
var result = ""
if(number <= 0){
return result
}
else{
if(number == 1){
result = result + 1
} else {
for(i = 1; i <= number; i++){
result = result + ',' + i;
}
}
}
return result
}
Thanks for all
You can simply add a flag (in the example "first") and check if this is your first iteration - if so, don't add a comma but set it to false ... see here: http://jsfiddle.net/fdfxc5zq/
var first = true; //have a flag that tells you if this is your first iteration - don't add a comma the first time around
for (i = 0; i <= number; i++) {
if (first) {
first = false;
} else {
result += ", ";
}
result += i;
}
Using your code, simply declare result with an initial value of 1 and start the for loop with i=2. Solved. (And in case of number being 1, just return result)
A one-liner for you:
return Object.keys(Array.apply(null,new Array(number))).map(function(n) {return +n+1;}).join(",");
Basically, creates an array of length number, "applies" it (basically ends up giving undefined values to each index), then uses Object.keys to get the indices of the array, increments all the items, then joins the whole thing with commas.
Two easy methods:
1) Just add a comma after each number and return a substring of length-1 to get rid of the last comma
if (i === 0) return ""; //to avoid substring() issues on empty strings
var result = "";
for (i = 0; i <= number; i++) {
result = i + ",";
}
return result.substr(0, result.length-1);
2) Using array and join
var result = [];
for (i = 0; i <= number; i++) {
result.push(i)
}
return result.join(); //default join separator is the comma
YourCommaSeparatedString.split(',');

pass $` value to associated parameter function of replace

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)

Categories