regex not working for phone number field - javascript

i have one phone number text-field.Now,i want to apply regex through java-script. for that i used below code.but it is not accept 10 digit.would any told me that what is wrong with below code.
java script code:-
function val(value) {
var p = phonevalue1
p = p.replace(/[^\d]*/gi, "")
if (p.length <= 5) {
value.value = p;
}
else if (p.length > 5 && p.length < 9) {
var a = p.substring(0, 5);
var b = p.substring(5, p.length);
var c = a + "-" + b;
value.value = c;
}
else if (p.length >= 9) {
var len = p.length;
var a = p.substring(0, 5);
var b = p.substring(5, len);
var c = a + "-" + b;
value.value = c.substring(0, 10);
}
}

From what I can tell you want the following
5 or less digits just add digits to value property of value object
6 - 8 digits add hyphen after fifth digit as in 12345-678
9 digits or greater 12345-6789
NOTES:
value.value means value is an {};
phonevalue1 is undefined in the function, so I will assume it is defined in the parent scope and is some string of numbers.
The code you have provided can be simplified a bit. I will make some adjustments and you'll have to adjust how your code block handles the function. K?
function val(value) {
var p = phonevalue1
p = p.replace(/[^\d]*/gi, "")
if (p.length <= 5) {
value.value = p;
}
else if (p.length > 5 && p.length < 9) {
var a = p.substring(0, 5);
var b = p.substring(5, p.length);
var c = a + "-" + b;
value.value = c;
}
else if (p.length >= 9) {
var len = p.length;
var a = p.substring(0, 5);
var b = p.substring(5, len);
var c = a + "-" + b;
value.value = c.substring(0, 10);
}
}
Change to this...
NOTE: Where value is your object as you stated,
var value = {};
var phonevalue1 = "12345";
var phonevalue2 = "12345678";
var phonevalue3 = "1234567890";
value.value = phonevalue1.replace(/(^\d{5})/, "$1-").replace(/-$/, '');
=> { value: "12345" };
value.value = phonevalue2.replace(/(^\d{5})/, "$1-").replace(/-$/, '');
=> { value: "12345-678" };
value.value = phonevalue3.replace(/(^\d{5})/, "$1-").replace(/-$/, '');
=> { value: "12345-67890" };
If you want to use a function as you have, I will try to make the same thing work, but the way your code is structured is not recommended as it is unnecessarily long and confusing.
function addHyphen( numString ){
return numString.replace(/(^\d{5})/, "$1-").replace(/-$/, '');
}
value.value = addHyphen( phonevalue1 );
Hope this helps...

Related

Function to generate specified number of random hex and rgb colors

Trying to write a function that generates a specified amount of random rgb or hex colors. It takes 'rgb' or 'hex'(type) and then 'n'(quantity to generate) as parameters, but I'm getting NaN when running code. Here's what I have written:
function generateColors(type, n) {
let result = ''
var quantity = Number(n)
if (type === 'rgb') {
let num = Math.round(0xffffff *
Math.random());
let r = num >> 16
let g = num >> 8 & 255
let b = num & 255
return ('rgb(' + r + ', ' + g + ', ' + b + ')') * quantity;
} else if (type === 'hexa') {
let hexDigits = '0123456789ABCDEF'
let randomHex= []
for (var i = 0; i < 6; i++) {
randomHex +=
hexDigits.charAt(Math.floor(Math.random() *
hexDigits.length));
}
return [randomHex] * quantity;
} else {
console.log('type not applicable')
}
return result
}
console.log(generateColors('rgb', 3))
console.log(generateColors('hexa', 3))
Not sure what I'm missing, or if I should do a switch statement instead, but any advice is welcome.
you will need to use loop...
you can loop n times inside the function. push the output into the result and return the result. it will look like something like this:
function generateColors(type, n) {
let result = [];
for (let x = 0; x < n; x++) {
if (type === "rgb") {
let num = Math.round(0xffffff * Math.random());
let r = num >> 16;
let g = (num >> 8) & 255;
let b = num & 255;
result.push("rgb(" + r + ", " + g + ", " + b + ")");
} else if (type === "hexa") {
let hexDigits = "0123456789ABCDEF";
let randomHex = "";
for (var i = 0; i < 6; i++) {
randomHex += hexDigits.charAt(
Math.floor(Math.random() * hexDigits.length)
);
}
result.push(randomHex);
} else {
console.log("type not applicable");
}
}
return result;
}
console.log("rgb", generateColors("rgb", 3));
console.log("hex", generateColors("hexa", 3));
Working example - dont forget to open the console ;)
Or, slightly shorter:
function mulcol(n,hex){
function rndcol(hex){
let col=[1,2,3].map(v=>Math.floor(Math.random()*256).toString(hex?16:10).padStart(hex?2:1,"0"));
return hex?`#${col.join("")}`:`rgb(${col.join(",")})`;
}
return [...Array(n)].map(v=>rndcol(hex));
}
console.log(mulcol(3)); // RGB output
console.log(mulcol(5,1));// hex output

You are given a two-digit integer n. Return the sum of its digits. Example For n = 29, the output should be addTwoDigits(n) = 11

More info:
Input/Output Details:
[time limit] 4000ms (js)
[input] integer n
A positive two-digit integer.
Constraints:
10 ≤ n ≤ 99.
[output] integer
The sum of the first and second digits of the input number.
Below is my attempt
function addTwoDigits(n) {
var num = n;
var n = num.toString();
var sum = n[0] + n[1];
return sum;
}
var userInput= prompt('enter a number');
if (userInput>= 10 && userInput<=99) {
return addTwoDigits(userInput);
}
console.log(addTwoDigits(n));
function addTwoDigits (input){
var numString = input.toString()
var numArray = numString.split('')
var digitOne = []
var digitTwo = []
for (var i = 0; i < numArray.length; i++){
digitOne.push(numArray[0])
digitTwo.push(numArray[1])
}
for (var i = 0; i < digitOne.length; i++){
digitOne.pop()
}
for (var i = 0; i < digitTwo.length; i++){
digitTwo.pop()
}
var numOne = parseInt(digitOne)
var numTwo = parseInt(digitTwo)
var sum = numOne + numTwo
return sum;
}
n[0] and n[1] are strings. + is only addition for two numbers, but concatenation for any other case, so "2" + "9" is back at "29" rather than 11 that you hope for. Use parseInt(n[0]) (and similar for n[1]) to turn them into something you can do arithmetic with.
Alternately, you can do this purely numerically, without ever touching strings:
var tens = Math.floor(n / 10);
var ones = n % 10;
var sum = tens + ones;
Here is my answer in Java.
int addTwoDigits(int n) {
String number = String.valueOf(n);
int[] nums = new int [number.length()];
for(int i = 0; i < number.length(); i++){
nums[i] = Character.getNumericValue(number.charAt(i));
}
return nums[0] + nums[1];
}
function solution(n) {
let number = n.toString();
console.log("Here is my number", );
let convertedNum = number.split('');
console.log("Here is my converted number: ", convertedNum.length)
let sum = 0;
for(let i = 0; i < convertedNum.length; i++){
sum += parseInt(convertedNum[i])
}
return sum;
}
Use parseInt
function addTwoDigits(n) {
var num = n;
var n = num.split("");
var sum = parseInt(n[0]) + parseInt(n[1]);
return sum;
}
var userInput = prompt('enter a number');
if (userInput >= 10 && userInput <= 99) {
console.log(addTwoDigits(userInput));
}
function addTwoDigits(n) {
let str = n.toString()
if (n >= 10 && n < 100){
return +str[0] + +str[1]
}
}
function solution(n) {
let a = Math.floor(n/10);
let b = n%10;
return a + b;
}
I used the charAt method and parseInt function to get an answer. You can see it in this code snippet:
function addTwoDigits(n) {
var string = n.toString();
var sum = parseInt(string.charAt(0)) + parseInt(string.charAt(1));
return sum;
}
var userInput = prompt('enter a number');
if (userInput >= 10 && userInput <= 99) {
console.log(addTwoDigits(userInput));
}
function addDigits(source) {
return source
/* convert number to string and split characters to array */
.toString().split('')
/* convert char[] to number[] */
.map(function (elm) { return Number(elm); })
/*
accumilate all numbers in array to value, which is initally zero.
REF: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce#Examples
*/
.reduce(function (result, current) { return result + current; }, 0)
}
function validate(source) {
if (typeof(source) == "undefined" || source == null) { throw 'value can not ne NULL ...'; }
if ((typeof(source) !== 'number')) { throw 'value has to of NUMBER type ....'; }
if ((source % 1)) { throw 'value has to be an INTEGER ....'; }
if (!(source >= 10 && source <= 99)) { throw 'value is out of range 10-99 ....'; }
}
/* TESTING ......*/
var samples = [null, 'sdsad', 9.9, 9, 10, 99, 100];
samples.forEach(function (elm) {
try {
validate(elm);
console.log(elm + ': ' + addDigits(elm));
} catch (exp) {
console.log(elm + ': ' + exp);
}
});
<
$(document).ready(function(){
var $number = $('input[name=number]'),
$result = $('.result');
$('input[name="calculate"]').on('click',function(){
var total = parseInt($number.val()),
decens = Math.floor(total/10),
units = total % 10;
if (total >9 && total < 100){
$result.html(decens + units);
}
else {
$result.html("Total must be an integer between 10 and 99");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="number" />
<input type="submit" name="calculate" value="Calculate"/>
Result:<span class="result"></span>
Here is a example from me
function solution(n) {
let num = n;
let num2 = n.toString().split("");
let sum = parseInt(num2[0]) + parseInt(num2[1]);
return sum;
}
Follow,
function solution(n) {
let num = n.toString().split('')
return parseInt(num.reduce((acc, cur) => Number(acc) + Number(cur), 0))
}
function solution(n) {
let num = n.toString().split('')
return parseInt(num.reduce((acc, cur) => Number(acc) + Number(cur), 0))
}
document.getElementById("input29").innerHTML = solution(29);
document.getElementById("input48").innerHTML = solution(48);
<!DOCTYPE html>
<html>
<body>
<h2>Example</h2>
Input 29: <p id="input29"></p>
<br>
Input 48: <p id="input48"></p>
</body>
</html>

for loop number sequence of (1,1,2,2,3,3, etc.)

I looked it up and this pattern is Hofstadter Female sequence. The equations are:
M(n) = n-F(M(n-1))
F(n) = n-M(F(n-1))
but I'm not sure how to put that into code.
So far I have:
while () {
_p++
_r++
if (_p % 2 === 0) {
_r = _p - 1;
}
}
Any help?
Without memoization:
function F(n)
{
return 0 < n ? n - M(F(n-1)) : 1
}
function M(n)
{
return 0 < n ? n - F(M(n-1)) : 0
}
var N = 10;
var f = [];
var m = [];
for (var i = 0; i <= N; ++i) {
f.push(F(i));
m.push(M(i));
}
console.log('F: ' + f.join(','))
console.log('M: ' + m.join(','))
Output:
F: 1,1,2,2,3,3,4,5,5,6,6
M: 0,0,1,2,2,3,4,4,5,6,6
http://jsfiddle.net/KtGBg/1/
Recursion should be avoided, if possible, so you can cache the already-calculated values for F(n) and M(n) :
var f = new Array();
var m = new Array();
function F(n){
if(f[n] != undefined) {
return f[n];
}
if (n==0) {
value = 1;
} else {
value = n - M(F(n-1));
}
f[n] = value;
return value;
}
function M(n){
if(m[n] != undefined) {
return m[n];
}
if (n==0) {
value = 0;
} else {
value = n - F(M(n-1));
}
m[n] = value;
return value;
}
This yields a much faster result for greater numbers (try it with 10000)
how about:
function F(n){
if (n==0) return 1
else return n - M(F(n-1))
}
function M(n){
if (n==0) return 0
else return n - F(M(n-1))
}
var str = ""
for(var i=0; i<=10; i++) str += F(i) + ", "
console.log(str.substr(0,str.length-2))
Similar to GaborSch's answer, you could use Doug Crockford's memoizer function, which can be found in Chapter 4 of Javascript: The Good Parts. Using memoization took the calculation time for the first 150 terms of the male and female Hofstadter sequences down to 256 ms as compared to almost 8 seconds without memoization.
var memoizer = function (memo, formula) {
var recur = function (n) {
var result = memo[n];
if (typeof result !== 'number') {
result = formula(recur, n);
memo[n] = result;
}
return result;
};
return recur;
};
var maleHofstadter = memoizer([0], function (recur, n) {
return n - femaleHofstadter(recur(n-1));
});
var femaleHofstadter = memoizer([1], function (recur, n) {
return n - maleHofstadter(recur(n-1));
});
var N = 150;
var f = [];
var m = [];
for (var i = 0; i <= N; ++i) {
f.push(femaleHofstadter(i));
m.push(maleHofstadter(i));
}
console.log('F: ' + f.join(','));
console.log('M: ' + m.join(','));

Javascript: Convert a number into a well formatted string

In javascript, I have some numbers.
23, 100000, 5000, 45.543
I want to convert each number into a well-formatted string
e.g.
'23.00', '1,000,000.00', '5,000.00' , '45.54'
How do I do that in javascript ?
I can do it easily in java (where there is a textformatter class for this)
thanks,
function CommaFormatted(amount)
{
var delimiter = ","; // replace comma if desired
var a = amount.split('.',2)
var d = a[1];
var i = parseInt(a[0]);
if(isNaN(i)) { return ''; }
var minus = '';
if(i < 0) { minus = '-'; }
i = Math.abs(i);
var n = new String(i);
var a = [];
while(n.length > 3)
{
var nn = n.substr(n.length-3);
a.unshift(nn);
n = n.substr(0,n.length-3);
}
if(n.length > 0) { a.unshift(n); }
n = a.join(delimiter);
if(d.length < 1) { amount = n; }
else { amount = n + '.' + d; }
amount = minus + amount;
return amount;
}

How to write a base32_decode in JavaScript?

I'm trying to create the equivalent of PHP's unpack. I've noticed the project PHPJS doesn't have it. I need it for the implementation of base32_encode and base32_decode (using Crockford's alphabet '0123456789ABCDEFGHJKMNPQRSTVWXYZ').
I couldn't find it anywhere and judging from it's counterpart, PHPJS's pack function I doubt my version will be complete and bug free any time soon.
base32tohex = (function() {
var dec2hex = function(s) {
return (s < 15.5 ? "0" : "") + Math.round(s).toString(16)
}
, hex2dec = function(s) {
return parseInt(s, 16)
}
, base32tohex = function(base32) {
for (var base32chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", bits = "", hex = "", i = 0; i < base32.length; i++) {
var val = base32chars.indexOf(base32.charAt(i).toUpperCase());
bits += leftpad(val.toString(2), 5, "0")
}
for (i = 0; i + 4 <= bits.length; i += 4) {
var chunk = bits.substr(i, 4);
hex += parseInt(chunk, 2).toString(16)
}
return hex
}
, leftpad = function(str, len, pad) {
return len + 1 >= str.length && (str = new Array(len + 1 - str.length).join(pad) + str),
str
};
return base32tohex;
}
)()

Categories