Regex using Javascript - javascript

I am trying to create a function that would remove certain characters from a phone number field. So far I have removed parenthesis, spaces, and hyphens as in (321) 321-4321. Also, I removed dots as in 321.321.4321. Lastly, I have validated when 11 digits and starting with 1 even with punctuation.
The code I input:
function phoneNumber(){
var number = '(321) 321-4321';
number = number.replace(/[^\d]/g, '');
return number;
}
I am now trying to have it return null for certain situations like:
When the number exceeds 11 digits
When letters and/or punctuation are present
When the area code does not start with 2-9
When the exchange code does not start with 2-9.
Any attempt to add a statement invalidates my original function. Can anyone help me I am new to regex, but I need help?

Brief
If I understand correctly, you want:
To remove any non-digit characters from the string
To get numbers that are 11 digits in length (or less)
To ensure the first and fourth digits in the number are in the range 2-9 (so not 0 or 1)
Code
The first regex can use \D instead of [^\d] as they both mean the exact same thing.
The second part can use any of the following methods (and more, but these are probably some of the simplest methods):
Regex and .length
/^[2-9]\d{2}[2-9]/.test(number) && number.length <= 11
var numbers = [
'(321) 321-4321',
'321.321.4321',
'123.456.7890',
'321.123.4567',
'(321) 321-4321-321'
];
function phoneNumber(number){
number = number.replace(/\D/g, '');
if(/^[2-9]\d{2}[2-9]/.test(number) && number.length <= 11) {
return number;
}
return null;
}
numbers.forEach(function(number){
console.log(phoneNumber(number));
});
charAt, regex and length
!/[01]/.test(number.charAt(0)) && !/[01]/.test(number.charAt(3)) && number.length <= 11
var numbers = [
'(321) 321-4321',
'321.321.4321',
'123.456.7890',
'321.123.4567',
'(321) 321-4321-321'
];
function phoneNumber(number){
number = number.replace(/\D/g, '');
if(!/[01]/.test(number.charAt(0)) && !/[01]/.test(number.charAt(3)) && number.length <= 11) {
return number;
}
return null;
}
numbers.forEach(function(number){
console.log(phoneNumber(number));
});
Regex (alone)
Obviously, you'd change 0 to whatever your minimum digits requirements are (minus 4); so if you want a minimum of 9, you'd put {5,7}.
/^[2-9]\d\d[2-9]\d{0,7}$/.test(number)
var numbers = [
'(321) 321-4321',
'321.321.4321',
'123.456.7890',
'321.123.4567',
'(321) 321-4321-321'
];
function phoneNumber(number){
number = number.replace(/\D/g, '');
if(/^[2-9]\d\d[2-9]\d{0,7}$/.test(number)) {
return number;
}
return null;
}
numbers.forEach(function(number){
console.log(phoneNumber(number));
});

Try as follows use .length to get characters in string
var number = '(321) 321-4321';
number = number.replace(/[^\d]/g, '');
console.log(number)
if (number.length > 11) {
console.log("null");
} else {
console.log(number.length);
}
if (number.match(/[a-z]/i)) {
console.log("alphabet letters found");
} else {
console.log("alphabet letters not found");
}

Related

How can I mask the digits in a alphanumeric string when the count of digits reaches 10?

I have an alphanumeric string, so I want to mask all the numbers in this string when the count of digits reaches 10. In this example, the digit count has reached the count of 10 two times irrespective of how many space, special character,s or digits are there
For ex:
string 1:- abc23 56 dfg %#34567fhgh0 1234567890 abc345
Output:- abc** ** dfg %#*****fhgh* ********** abc345
It ignores the characters and mask the number when the digit length reaches 10. I want to do this with regex. How can I do that?
You may use something like this:
if ((s.match(/\d/g) || []).length >= 10) {
s = s.replace(/\d/g, '*');
}
This will count the number of digit matches. If there are 10 or more digits, it replaces each one with a '*' character. If you want to only replace the digits if the string contains at least one set of 10 consecutive digits, see the end of the answer.
Here's a complete example:
var arr = ['abc23 56 dfg %#34567fhgh0 1234567890 abc345', 'abc123def'];
for (var i = 0; i < arr.length; i++) {
let s = arr[i];
if ((s.match(/\d/g) || []).length >= 10) {
s = s.replace(/\d/g, '*');
arr[i] = s;
}
console.log(s);
}
Output:
abc** ** dfg %#*****fhgh* ********** abc***
abc123def
If you want the condition to be for 10 consecutive digits, use the following instead:
if (/\d{10}/g.test(s)) {
s = s.replace(/\d/g, '*');
}
You could split() the string into an array, check the length of the string, if it is over 10, then map the mask character where the number was using splice and its key along with Number and isNan.
var str = 'abc23 56 dfg %#34567fhgh0 1234567890'
var str2 = 'abc345'
var str3 = '%#34567fhg7'
var str4 = '1234567890'
const exchange = (str, cap) => {
// split the string and define array
const arr = str.split('')
// condtional to see if string.length is greater than cap
if (str.length > cap) {
// we have a string longer than cap, loop over the array, exclude
// empty spaces and check if value is a number using isNaN, if it is,
// we splice its value using the key with the mask character x
arr.map((char, k) => char !== ' ' ? Number.isNaN(Number(char)) ? null : arr.splice(k, 1, 'x') : null)
// return the value as a string by joining the array values together
return arr.join('')
} else {
// return the string as its length is not more than cap
return str
}
}
console.log(`${exchange(str, 10)}, length = ${str.length}`)
console.log(`${exchange(str2, 10)}, length = ${str2.length}`)
console.log(`${exchange(str3, 10)}, length = ${str3.length}`)
console.log(`${exchange(str4, 10)}, length = ${str4.length}`)

Is it possible to only convert the letters and not also the numbers

Is it possible to only convert the letters after 4 numbers. With not converting the numbers also. I use charCodeAt to do this.
What I want to do is only converting letters and not the numbers. Below I also convert the numbers. I want to convert things after the first 4 characters, the letters are converted to ascii numbers.
function convertZipcodeToInteger(letters){
letters = letters;
for(var i = 0; i < letters.length; i++){
let number = letters.charCodeAt(i) % 65 + "";
if (number.length < 2)
{
number = "0" + number;
}
console.log(number);
}
} convertZipcodeToInteger('7711AD');
What I am doing right now with the code is putting 7711AD into the letters parameter. Putting them through an for loop, so it converts all the letters(and numbers) with charCodeAt. When the number.length is smaller then 2 it gets a 0 in front of it.
What I want to do is convert it to this: 77110003 this is with the converted letters. I don't want the numbers converted, because they don't need to change.
You could test if the value is a number and if not take the letter and convert it to a numerical value based 36 and pad it before returning.
function convertZipcodeToInteger(string) {
function pad2(s) { return ('00' + s.toString()).slice(-2); }
return string
.split('')
.map(function (c) {
return /\d/.test(c)
? c
: pad2(parseInt(c, 36) - 10);
})
.join('')
};
function convertZipcodeToLetter(string) {
return string.slice(0, 4) + string
.slice(4)
.split(/(?=(?:..)*$)/)
.map(function (s) { return (+s + 10).toString(36).toUpperCase(); })
.join('');
}
console.log(convertZipcodeToInteger('7711AD'));
console.log(convertZipcodeToLetter('77110003'));
Is it possible to only convert the letters after 4 numbers.
Simply start your for-loop from 4
for(var i = 4; i < letters.length; i++){ //notice var i = 4
Edit
Looks like you want to replace letters every time they occur, not necessarily after 4 numbers,
"7711AD".replace(/[a-z]/gi, function(match){ return ( "0" + match.charCodeAt( 0 ) % 65).slice( -2 ) });
Demo
"7711AD".replace(/[a-z]/gi, function(match) {
return ( "0" + match.charCodeAt(0) % 65).slice( -2 ); //ensuring that single digit is padded with 0
});
Your question is a bit hard to understand but this is what I think you are after:
it can also be done without the function with just regexp magic
first 4 charaters are numbers and should only have 0 added (eg 07)
then 2 letters which should be encoded from 0-26 and always be two charaters long
function convertZipcodeToInteger(letters){
for(var i = 0; i < letters.length; i++){
let number = letters[i];
if (i>3) { number = letters.charCodeAt(i) % 65 + ""; }
if (number.length < 2) {
number = "0" + number;
}
console.log(number);
}
} convertZipcodeToInteger('7711AD');

Convert number to alphabet letter

I want to convert a number to its corresponding alphabet letter. For example:
1 = A
2 = B
3 = C
Can this be done in javascript without manually creating the array?
In php there is a range() function that creates the array automatically. Anything similar in javascript?
Yes, with Number#toString(36) and an adjustment.
var value = 10;
document.write((value + 9).toString(36).toUpperCase());
You can simply do this without arrays using String.fromCharCode(code) function as letters have consecutive codes. For example: String.fromCharCode(1+64) gives you 'A', String.fromCharCode(2+64) gives you 'B', and so on.
Snippet below turns the characters in the alphabet to work like numerical system
1 = A
2 = B
...
26 = Z
27 = AA
28 = AB
...
78 = BZ
79 = CA
80 = CB
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var result = ""
function printToLetter(number){
var charIndex = number % alphabet.length
var quotient = number/alphabet.length
if(charIndex-1 == -1){
charIndex = alphabet.length
quotient--;
}
result = alphabet.charAt(charIndex-1) + result;
if(quotient>=1){
printToLetter(parseInt(quotient));
}else{
console.log(result)
result = ""
}
}
I created this function to save characters when printing but had to scrap it since I don't want to handle improper words that may eventually form
Just increment letterIndex from 0 (A) to 25 (Z)
const letterIndex = 0
const letter = String.fromCharCode(letterIndex + 'A'.charCodeAt(0))
console.log(letter)
UPDATE (5/2/22): After I needed this code in a second project, I decided to enhance the below answer and turn it into a ready to use NPM library called alphanumeric-encoder. If you don't want to build your own solution to this problem, go check out the library!
I built the following solution as an enhancement to #esantos's answer.
The first function defines a valid lookup encoding dictionary. Here, I used all 26 letters of the English alphabet, but the following will work just as well: "ABCDEFG", "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", "GFEDCBA". Using one of these dictionaries will result in converting your base 10 number into a base dictionary.length number with appropriately encoded digits. The only restriction is that each of the characters in the dictionary must be unique.
function getDictionary() {
return validateDictionary("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
function validateDictionary(dictionary) {
for (let i = 0; i < dictionary.length; i++) {
if(dictionary.indexOf(dictionary[i]) !== dictionary.lastIndexOf(dictionary[i])) {
console.log('Error: The dictionary in use has at least one repeating symbol:', dictionary[i])
return undefined
}
}
return dictionary
}
}
We can now use this dictionary to encode our base 10 number.
function numberToEncodedLetter(number) {
//Takes any number and converts it into a base (dictionary length) letter combo. 0 corresponds to an empty string.
//It converts any numerical entry into a positive integer.
if (isNaN(number)) {return undefined}
number = Math.abs(Math.floor(number))
const dictionary = getDictionary()
let index = number % dictionary.length
let quotient = number / dictionary.length
let result
if (number <= dictionary.length) {return numToLetter(number)} //Number is within single digit bounds of our encoding letter alphabet
if (quotient >= 1) {
//This number was bigger than our dictionary, recursively perform this function until we're done
if (index === 0) {quotient--} //Accounts for the edge case of the last letter in the dictionary string
result = numberToEncodedLetter(quotient)
}
if (index === 0) {index = dictionary.length} //Accounts for the edge case of the final letter; avoids getting an empty string
return result + numToLetter(index)
function numToLetter(number) {
//Takes a letter between 0 and max letter length and returns the corresponding letter
if (number > dictionary.length || number < 0) {return undefined}
if (number === 0) {
return ''
} else {
return dictionary.slice(number - 1, number)
}
}
}
An encoded set of letters is great, but it's kind of useless to computers if I can't convert it back to a base 10 number.
function encodedLetterToNumber(encoded) {
//Takes any number encoded with the provided encode dictionary
const dictionary = getDictionary()
let result = 0
let index = 0
for (let i = 1; i <= encoded.length; i++) {
index = dictionary.search(encoded.slice(i - 1, i)) + 1
if (index === 0) {return undefined} //Attempted to find a letter that wasn't encoded in the dictionary
result = result + index * Math.pow(dictionary.length, (encoded.length - i))
}
return result
}
Now to test it out:
console.log(numberToEncodedLetter(4)) //D
console.log(numberToEncodedLetter(52)) //AZ
console.log(encodedLetterToNumber("BZ")) //78
console.log(encodedLetterToNumber("AAC")) //705
UPDATE
You can also use this function to take that short name format you have and return it to an index-based format.
function shortNameToIndex(shortName) {
//Takes the short name (e.g. F6, AA47) and converts to base indecies ({6, 6}, {27, 47})
if (shortName.length < 2) {return undefined} //Must be at least one letter and one number
if (!isNaN(shortName.slice(0, 1))) {return undefined} //If first character isn't a letter, it's incorrectly formatted
let letterPart = ''
let numberPart= ''
let splitComplete = false
let index = 1
do {
const character = shortName.slice(index - 1, index)
if (!isNaN(character)) {splitComplete = true}
if (splitComplete && isNaN(character)) {
//More letters existed after the numbers. Invalid formatting.
return undefined
} else if (splitComplete && !isNaN(character)) {
//Number part
numberPart = numberPart.concat(character)
} else {
//Letter part
letterPart = letterPart.concat(character)
}
index++
} while (index <= shortName.length)
numberPart = parseInt(numberPart)
letterPart = encodedLetterToNumber(letterPart)
return {xIndex: numberPart, yIndex: letterPart}
}
this can help you
static readonly string[] Columns_Lettre = new[] { "A", "B", "C"};
public static string IndexToColumn(int index)
{
if (index <= 0)
throw new IndexOutOfRangeException("index must be a positive number");
if (index < 4)
return Columns_Lettre[index - 1];
else
return index.ToString();
}

Array not sorting correctly in javascript

I have a Javascript array of strings that I'm sorting using the compareFunction. For the most part, it's sorting correctly:
JS
array = ["E10N1", "E10N3", "E10N10", "E10N2", "E10N4", "E10N9", "E10N5", "E10N8", "E10N6", "E10N7"];
function sortStrings(a, b){
if(a < b){
return -1;
}
if(a > b){
return 1;
}
return 0;
}
array.sort(sortStrings);
for(var i = 0; i < array.length; i++){
$(".table_body").append("<div class='table_row'><p>" +array[i] +"</p></div>");
}
The issue I'm having is the sort function is putting the "E10N10" item between"E10N1" and "E10N2" items. So it looks like this:
I understand that sorting strings is done alphabetically, but wouldn't the "E10N10" string still be processed as later than "E10N9"? How do I fix it to have this particular string come last in the array after it's sorted?
You can modify your custom sorting function to handle this. For example, if all of your strings start with 4 characters that you don't care about when sorting, just do this:
function sortStrings(a, b){
a = parseInt(a.substr(4));
b = parseInt(b.substr(4));
if(a < b){
return -1;
}
if(a > b){
return 1;
}
return 0;
}
In alphabetical sort, it just looks at the characters sequentially so "E10N1" would be before "E10N9", even though there is another character after the "E10N1". Just like "abcd" comes before "abd".
If you really want the type of sort you're asking for, it is going to take a much more complicated custom sort algorithm that actually parses the numeric parts of the tag to do actual numeric comparisons (not alphabetic sorts) on them.
Here's is a sorting scheme that sorts based on the trailing digits:
var array = ["E10N1", "E10N3", "E10N10", "E10N2", "E10N4", "E10N9", "E10N5", "E10N8", "E10N6", "E10N7"];
var regex = /\d+$/;
function getLastNum(str) {
var m = str.match(regex);
if (m) {
return parseInt(m[0], 10);
} else {
return -1;
}
}
array.sort(function(a, b) {
return getLastNum(a) - getLastNum(b);
});
document.write(JSON.stringify(array));
You can obviously make this as complicated or rich as desired. For example, if you want to identify all numeric sequences in the number and turn each of them into actual numbers, you can do that too. You did not specify how involved this needs to be so I showed the smallest work required to make your specific sequence work (by sorting just by the trailing digits).
For a discussion of several different general purpose algorithms for handling mixed alpha-numeric sorts where the digits can occur anywhere in the string and can occur in multiple places, you can see this article: Sorting for Humans: Natural Sort Order. One particular implementation in Javascript can be found here.
The general idea behind the generic algorithm is as follows:
Get the next character of each string
If not both digits, then compare the characters directly and return the result
If both digits, then collect sequence of digits in both strings
Longest sequence of consecutive digits is higher
While accumulating sequential digits, keep track of which sequence
has the first non-equal digit that is higher than the other
If sequences were the same length, then the previous collected value
of which sequence had the first different higher number determines
which sequence comes first
If sequence of digits or single character were equal, go to next character
and start the above process over
One advantage of this generic algorithm is that it does not actually convert the numeric sequences of digits to a number so it will work on sequences of numbers of arbitrary length without running into limitations on how many digits a number can be in Javascript.
Depending upon your desired algorithm, you may or may not want to ignore whitespace preceding digits and you may or may not want to account for plus or minus signs in front of numbers. And, you may want to use a language aware comparison rather than a strict ascii code comparison. There are lots of factors to consider for any particular use.
Here is a general purpose algorithm that I wrote from scratch:
var array = ["E10N1", "E10N3", "E10N10", "E10N2", "E10N4", "E10N9", "E10N5",
"E10N8", "E10N6", "E10N7", "C10N1", "D10N3", "E11N10", "E09N2", "E999N4",
"E10000N9", "g10N6", "z10N6", "q10N6", "R10N6", "E001N1", "E00N1",
"E0000N1", "zN1", "zN000", "zN00", "000", "00", "0001", "0002", "A00",
"A", "0A"];
// return negative value if a < b
// return 0 if a === b
// return positive value if a > b
//
// Rules:
// - Sort characters before numbers
// - Ignore leading zeroes on digits
// - Ignore plus/minus signs in front of digits
// - For sequences of zeroes the shorter sequence is first
//
function alphaNumCompare(a, b) {
var aIndex = 0,
bIndex = 0,
aChar, bChar, result;
function isDigit(ch) {
return ch >= "0" && ch <= "9";
}
function compareNums() {
// aChar, bChar contain first digit
// get rest of consecutive digits and compare
// returns negative, 0 or positive
// as side affect, advances aIndex and bIndex to next non-numeric
var aZeroLen = 0,
bZeroLen = 0,
aNumStr = "",
bNumStr = "";
// collect consecutive digits from a and b
// ignore any leading zeroes
if (aChar === "0") {
++aZeroLen;
} else {
aNumStr = aChar;
}
if (bChar === "0") {
++bZeroLen;
} else {
bNumStr = bChar;
}
while (aIndex < a.length) {
aChar = a.charAt(aIndex);
if (!isDigit(aChar)) {
break;
}
++aIndex;
// don't add leading zeroes and keep a count of leading zeroes
if (aChar === "0" && aNumStr === "") {
++aZeroLen;
} else {
aNumStr += aChar;
}
}
while (bIndex < b.length) {
bChar = b.charAt(bIndex);
if (!isDigit(bChar)) {
break;
}
++bIndex;
// don't add leading zeroes and keep a count of leading zeroes
if (bChar === "0" && bNumStr === "") {
++bZeroLen;
} else {
bNumStr += bChar;
}
}
// we now have a series of consecutive digits in aNumStr and bNumStr
if (aNumStr.length === bNumStr.length) {
// check for nothing but leading zeroes in both
if (aNumStr.length === 0) {
return aZeroLen - bZeroLen;
}
if (aNumStr === bNumStr) {
return 0;
} else {
return aNumStr < bNumStr ? -1 : 1;
}
} else {
// lengths are not equal, then shorter string comes first
return aNumStr.length - bNumStr.length;
}
}
// loop while both strings have characters left
while (aIndex < a.length && bIndex < b.length) {
aChar = a.charAt(aIndex++);
bChar = b.charAt(bIndex++);
if (isDigit(aChar) && isDigit(bChar)) {
result = compareNums();
if (result !== 0) {
return result;
}
} else {
// not both numeric, just compare the characters themselves
result = aChar.localeCompare(bChar);
if (result !== 0) {
return result;
}
}
}
// shorter one is first
return (a.length - aIndex) - (b.length - bIndex);
}
array.sort(alphaNumCompare);
document.write(JSON.stringify(array).replace(/,/g, ", "));
The logic for this is as follows:
Implement a custom sort function for the Array sort() function.
Get next character in the string
If both are digits, then accumulate whatever sequence of consecutive digits there are.
Trim leading zeroes from the sequence of zeroes
If both sequences are only a sequence of zeroes, then the shorter one is less
The shorter sequence of numbers is less than the longer one
If both sequences of numbers are the same length, then you can just do a straight string compare on them to get the result
If both characters are not digits, then just compare them as a string
If strings have compared equal up to the point where one ends, then the shorter one is less
I suggest to use a kind of sort pattern for this special purpopse.
var data = ["E10N1", "E10N3", "E10N10", "E10N2", "E10N4", "E10N9", "E10N5", "E10N8", "E10N6", "E10N7"],
result = data.map(function (el, i) {
var a = /(\D*)(\d*)(\D*)(\d*)/i.exec(el);
a.shift();
return { index: i, value: a };
}).sort(function (a, b) {
var i = 0, r = 0;
while (r === 0 && i < a.value.length && i < b.value.length) {
r = i % 2 ? +a.value[i] - +b.value[i] : a.value[i].localeCompare(b.value[i]);
i++;
}
return r;
}).map(function (el) {
return data[el.index];
});
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
You could use a regex to capture the digits at the end of each element and sort on those instead:
function sortStrings(a, b) {
var regex = /E10N([\d]+)/;
var apost = +a.match(regex)[1];
var bpost = +b.match(regex)[1];
if (apost < bpost) return -1;
if (apost > bpost) return 1;
return 0;
}
DEMO
In ASCII order 1 is less than 9 so "E10N10" is less than "E10N9". To get result you want, you need sorts the numbers in value order, while sorting the non-numbers in ASCII order. You can use this Alphanum Algorithm:
http://www.davekoelle.com/alphanum.html

How to check if a digit is used in a number multiple times

Example: We have the number 1122. I would like to check that if given number contains the digit 1 more than once. In this case, it should return true.
I need the code to be flexible, it has to work with any number, like 3340, 5660, 4177 etc.
You can easily "force" JS to coerce any numeric value to a string, either by calling the toString method, or concatenating:
var someNum = 1122;
var oneCount = (someNum + '').split('1').length;
by concatenating a number to an empty string, the variable is coerced to a string, so you can use all the string methods you like (.match, .substring, .indexOf, ...).
In this example, I've chosen to split the string on each '1' char, count and use the length of the resulting array. If the the length > 2, than you know what you need to know.
var multipleOnes = ((someNum + '').split('1').length > 2);//returns a bool, true in this case
In response to your comment, to make it flexible - writing a simple function will do:
function multipleDigit(number, digit, moreThan)
{
moreThan = (moreThan || 1) + 1;//default more than 1 time, +1 for the length at the end
digit = (digit !== undefined ? digit : 1).toString();
return ((someNum + '').split(digit).length > moreThan);
}
multipleDigit(1123, 1);//returns true
multipleDigit(1123, 1, 2);//returns false
multipleDigit(223344,3);//returns 3 -> more than 1 3 in number.
Use javascript's match() method. Essentially, what you'd need to do is first convert the number to a string. Numbers don't have the RegExp methods. After that, match for the number 1 globally and count the results (match returns an array with all matched results).
​var number = 1100;
console.log(number.toString().match(/1/g).length);​
function find(num, tofind) {
var b = parseInt(num, 10);
var c = parseInt(tofind, 10);
var a = c.split("");
var times = 0;
for (var i = 0; i < a.length; i++) {
if (a[i] == b) {
times++;
}
}
alert(times);
}
find('2', '1122');
Convert the number to a string and iterate over it. Return true once a second digit has been found, for efficiency.
function checkDigitRepeat(number, digit) {
var i, count = 0;
i = Math.abs(number);
if(isNaN(i)) {
throw(TypeError('expected Number for number, got: ' + number));
}
number = i.toString();
i = Math.abs(digit);
if(isNaN(i)) {
throw(TypeError('expected Number for digit, got: ' + digit));
}
digit = i.toString();
if(digit > 9) {
throw(SyntaxError('expected a digit for digit, got a sequence of digits: ' + digit));
}
for(i = 0; i < number.length; i += 1) {
if(number[i] === digit) {
count += 1;
if(count >= 2) { return true; }
}
}
return false;
}
In the event that you want to check for a sequence of digits, your solution may lie in using regular expressions.
var myNum = '0011';
var isMultipleTimes = function(num) {
return !!num.toString().match(/(\d)\1/g);
}
console.log(isMultipleTimes(myNum));
JavaScript Match
Using #Aspiring Aqib's answer, I made a function that actually works properly and in the way I want.
The way it works is:
Example execution: multDig('221','2')
Split the number (first argument) to an array where each element is one digit.Output: ['2','2','1']
Run a for loop, which checks each of the array elements if they match with the digit (second argument), and increment the times variable if there is a match.Output: 2
Check inside the for loop if the match was detected already to improve performance on longer numbers like 2211111111111111
Return true if the number was found more than once, otherwise, return false.
And finally the code itself:
function multDig(number, digit){
var finalSplit = number.toString().split(''), times = 0;
for (i = 0; i < finalSplit.length; i++){
if (finalSplit[i] == digit){
times++
}
if (times > 1){
return true;
}
}
return false;
}

Categories