Javascript Numbers and Comma with input pattern [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Hi I need to combine 2 error checking procedures. I dont use jquery
I only want these values appear 0123456789,
My HTML, i need to know the pattern for other instances of my website
<input type="text" pattern="?" maxlength="10" id="f2f11c3" value="0"></input>
My JS
document.getElementById("f2f11c3").addEventListener("keyup", function(){addcommas("f2f11c3")}, false);
.
function addcommas(id)
{
//i dont know what to place here
//every 3 numbers must have a comma
//ie. input is 123.c39,1mc
//it must also remove if a comma is placed manually
//result must be 123,391
}
Hope someone could help. Thanks!

document.getElementById('f2f11c3').
addEventListener("input", function(){addcommas();}, false);
function addcommas()
{
var v = document.getElementById('f2f11c3');
var t = v.value.replace(/\D/g, '');
var i,temp='';
for(i=t.length; i>=0;i-=3){
if(i==t.length) {
temp=t.substring(i-3,i);
}
else
{
if(t.substring(i-3,i)!="")
temp = t.substring(i-3,i)+','+temp;
}
if(i<0) {temp=t.substring(0,i+3)+','+temp; break;}
}
v.value = temp;
}
DEMO

function addcommas(id) {
var arr = [];
// loop over the id pushing numbers into the array
for (var i = 0, l = id.length; i < l; i++) {
if (id[i] >= 0 && id[i] <= 9) {
arr.push(id[i]);
}
}
// loop over the array splicing in commas at every 3rd position
for (var i = 0, l = arr.length; i < l; i += 3) {
arr.splice(i, 0, ',');
i++;
l++;
}
// remove the first unnecessary comma
arr.shift()
// return the comma-separated string
return arr.join('');
}
DEMO

The id is an HTML element's id, not the value
function addcommas(id)
{
//Not really needed, but just to shorten the details below
var x = document.getElementById(id);
//Current value but removes anything aside from numbers 0-9 and comma (not really needed)
var curval = x.value.replace(/[^\d,]/g,'');
//Strips the comma from the current value if someone entered it manually.
var nocomma = x.value.replace(/[^\d]/g,'');
//If not blank, prevent NAN error
if (nocomma.length>0)
{
//Converts text to int
nocomma = parseInt(nocomma, 10);
//Dont know why, but doesnt work without this
nocomma = nocomma+0;
//Converts it back to string to add the comma
nocomma = nocomma+"";
//Adds comma every 3 numbers, I got this from other research, dont know how it works
x.value = nocomma.replace(/(\d)(?=(\d{3})+$)/g, '$1,');
}
}
My Input in the HTML is as follows
//for iphone, this will popout the numberpad with choices 0-9 only. Easier to type, better mobile usability.
<input type="text" pattern="\d*" maxlength="12" id="f2f11c3" value="0"></input>

Related

Why Random variable is only returning 1 character [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 11 months ago.
Improve this question
Hey guys im trying to generate a random password using upper and lowercase keys + numbers. the code seems to work but instead of returning 20 characters its instead returning only 1. The return seems random.
The element should be replaced why the random password every time the button is clicked.
HTML
<button id = "button5" onclick = "password()">Generate password </button>
<p4 id = "p4" > Your password will apear here </p4>
This is the Javascript
function password (length ) {
var ranpassword = "";
var chara = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var charalength = chara.length // there is an outside variable defining charalength = ""; I could not include that here
for (var i = 0; <length ; i++) {
ranpassword += chara.charAt(Math.floor(Math.random() *
chara.length));
return ranpassword;
}
document.getElementById("p4").innerHTML = "hello there " + ranpassword;
console.log(password(20));
}
whenver the button is clicked, one random letter is returned in console.log and i cant seem to understand why ? Can anyone tell me why?
Any help would be great . Thanks :)
You did some mistake. Try this code,
function password (length) {
let ranpassword = "",
chara = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ",
charalength = chara.length;
for (var i = 0; i<length ; i++) {
ranpassword += chara.charAt(Math.floor(Math.random() *
chara.length));
}
document.getElementById("p4").innerHTML = "hello there " + ranpassword;
}
<button id = "button5" onclick="password(20)">Generate password </button>
<p4 id = "p4" > Your password will apear here </p4>
Aside from your password function implementation partly wrong, you are not passing a length to password() function in your onclick handler.
You need to pass the length as well like password(20):
<button id = "button5" onclick = "password(20)">Generate password </button>
as #Locke said, your for loop syntax is incorrect, as You are missing i in the comparison. Other than that, you code is flooded with typos. You didn't close the for loop, and you didn't need to return ranpassword. Now your code works, notice that the number I put as a parameter in the onclick in the HTML is the length your password will be. Also, instead of using .chatAt, I generate a random number and add it to ranpassword. For example: The for loop gets chara[4], so randpassword has chara's 5th letter.
function password(length) {
var ranpassword = "";
var chara = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var charalength = chara.length // there is an outside variable defining charalength = ""; I could not include that here
for (var i = 0; i < length; i++) {
ranpassword += chara[(Math.floor(Math.random() *
chara.length))];
}
document.getElementById("p4").innerHTML = "hello there " + ranpassword;
}
<button id = "button5" onclick = "password(4)">Generate password </button>
<p4 id = "p4" > Your password will apear here </p4>
I have fixed the problem
function password(length) {
var ranpassword = "";
var chara = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var charalength = chara.length;
for (var i = 0; i < length; i++) {
ranpassword += chara.charAt(Math.floor(Math.random() * chara.length));
}
return ranpassword;
}
console.log(password(5));
you were returning the password form the loop so it was returning a single character

Need to have one string from Looped Chars JS [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
need to get the output as 1 string instead of looped string
the output I got each letter on its own
need to have the second output which is one word
Thanks in advance:D
let start = 0;
let swappedName = "elZerO";
for (let i = start; i<swappedName.length; i++){
if (swappedName[i] == swappedName[i].toUpperCase()) {
console.log(swappedName[i].toLowerCase());
}else {
console.log(swappedName[i].toUpperCase());
}
}
//Output
E
L
z
E
R
o
// Need to be
"ELzERo"
Use string = string0+string1 , or keep adding values to an array, then join the array with array.join()
MasteringJs has a great guide on ways to merge characters and strings.
let start = 0;
let swappedName = "elZerO";
var outputString="";
var outputStringArray=[];
var newChar="";
for (let i = start; i<swappedName.length; i++){
if (swappedName[i] == swappedName[i].toUpperCase()) {
newChar = swappedName[i].toLowerCase();
}else {
newChar=swappedName[i].toUpperCase();
}
outputStringArray.push(newChar);
outputString+=newChar;
}
console.log("[Output using string1 + string 2] is "+outputString); // Another example of concating string
console.log("[Output using array.join] is "+outputStringArray.join("")); // Another example of concating string
// Need to be
"ELzERo"

Get last "ordered" number [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I've been struggling with the definition of a function. It must take a positive number N as a parameter and return the last ordered number. By "ordered" number I mean that every digit follow each other.
Example1 : Takes 1000 as a parameter and returns 789.
Example2 : Takes 500 as a parameter and returns 456.
Here's working code. Although I don't like just giving you the answer. This is something you have to practice and learn how to do on your own. Take the time to understand what I did. Also, this solution can be improved a lot, just something that I did quickly and works.
The algorithm in action:
function calc() {
//Get the number in the text input
var nbr = parseInt(document.getElementById("number").value, 10);
//Loop starting from the top
for (var i = nbr; i > 0; i--) {
if (isOrderedNumber(i)) {
document.getElementById("result").innerText = i;
return;
}
}
document.getElementById("result").innerText = "None found";
}
function isOrderedNumber(number) {
var digits = number.toString().split('');
//Loops in the digits of the number
for (var i = 0; i < digits.length - 1; i++) {
//Check if the current number+1 is not equal to the next number.
if (parseInt(digits[i]) + 1 !== parseInt(digits[i + 1])) {
return false;
}
}
return true;
}
<input id="number" type="text" />
<button onclick="calc()">Find last ordered number</button>
<br/>
<br/>
<span id="result"></span>
In you case, instead of using html element you would receive "nbr" by parameter instead and would return the value instead of putting the value in the html element. Ask if you have any questions on how this works.

Masking number at a particular position [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have a input field with a maximum length of 15 character.
i want to do something like this
original number :784198012345671
should be: 784********5671
The process to achieving what you want varies depending on whether:
you want to mask the value after the it has been entered or
you want to mask the value during typing.
If you want to do this, after the value has been entered the following should do the trick.
Snippet:
var
/* The original value. */
n = "784198012345671",
/* The masked value. */
masked = n.slice(0, 3) + Array(8).join("*") + n.slice(-4);
/* Log the result. */
console.log(masked);
If, instead, you want to mask the input during typing, things get more complicated.
Snippet:
$(".newsocial").on("keyup", function(e) {
/* Turn the value into an array of characters. */
var value = this.value.split("");
/* Iterate over every character. */
value.forEach(function (char, index) {
/* Replace the character with a placeholder when appropriate. */
if (index >= 3 && index <= 10) value[index] = "*";
});
/* Turn the array of chars into a string & assign it to the value of the input. */
this.value = value.join("");
})
<!--- HTML --->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" maxlength="15" id="input-card" class="newsocial">
const original = "784198012345671",
obfuscated = original.substr(0, 3) + "*".repeat(original.length - 7) + original.substr(-4);
You may use substr to get the number groups at the beginning and the end out of the number and then use repeat to fill the asterisks inbetween.
Convert your number to string and use string.prototype.substring and string.prototype.repeate to build parts:
var number = 784198012345671;
number = number.toString();
var res = number.substring(0, 3) + '*'.repeat(8) + number.substring(11, 15);
console.log(res);
Replace Integer to String
Iterate the string and replace the position with *:
let number = 123455666777888;
let stringedNum = number.toString();
for(i=0;i<stringedNum.length;i++) {
if(i>5 && i<10) { // change this line as per your need
console.log(i)
stringedNum = stringedNum.replace(stringedNum[i],'*');
}
}
console.log(stringedNum)

JavaScript prototypes - technical interview [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I had a JavaScript interview last wednesday, and I had trouble with one of the questions. Maybe you guys can give me hand with it?
The question was: how would you go about this printing var a and s to the console, in camel case, with the help of a prototype function...
var s = “hello javier”;
var a = “something else”;
String.prototype.toCamelCase = function() {
/* code */
return capitalize(this);
};
...so the result is the same as doing this?
console.log(s.toCamelCase());
console.log(a.toCamelCase());
>HelloJavier
>SomethingElse
Thanks!
var s = 'hello javier';
var a = 'something else';
String.prototype.toCamelCase = function() {
return capitalize(this);
};
function capitalize(string) {
return string.split(' ').map(function(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}).join('');
}
console.log(a.toCamelCase());
console.log(s.toCamelCase());
Reference
How do I make the first letter of a string uppercase in JavaScript?
I would go with something like this:
var s = "hello javier";
var a = "something else";
String.prototype.toCamelCase = function() {
function capitalize(str){
var strSplit = str.split(' ');
// starting the loop at 1 because we don't want
// to capitalize the first letter
for (var i = 1; i < strSplit.length; i+=1){
var item = strSplit[i];
// we take the substring beginning at character 0 (the first one)
// and having a length of one (so JUST the first one)
// and we set that to uppercase.
// Then we concatenate (add on) the substring beginning at
// character 1 (the second character). We don't give it a length
// so we get the rest.
var capitalized = item.substr(0,1).toUpperCase() + item.substr(1);
// then we set the value back into the array.
strSplit[i] = capitalized;
}
return strSplit.join('');
}
return capitalize(this);
};
// added for testing output
console.log(s.toCamelCase());
console.log(a.toCamelCase());

Categories

Resources