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.
Related
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"
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)
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());
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>
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
For example :
Var1 = 289.56
I use this formula :
foundStr = Var1.match("[0-9]+\.[0-9]+");
Price( parseFloat(foundStr).toFixed(2) );
But when Var1 > 999.99 (Example : 2,356.21)
What is the script find the string ?
foundStr = Var1.match(??);
Thank you
You already have a numeric variable, why are you messing with strings?
var number1 = 289.56;
if (number1 > 999.99) {
// do whatever
}
If you're trying to round, use Math.floor instead:
var number1 = 289.56485345734593453;
var roundedNumber1 = Math.floor(number1 * 10) / 10; // two decimal points
I think you just want to remove the commas and check if its a float, but its hard to tell based off your question. How about something like this:
var Var1 = "1,234.567";
var parsed = parseFloat(Var1.replace(",",""), 10);
if (isNaN(parsed)) {
// its not a valid number, so deal with it as needed
}
else {
// parsed now holds your Number, so use it
}
This approach will work regardless of if the number is >= 1000.
var Var1 = "2,356.21";
foundStr = String(Var1.match(/([0-9]{1,3},)?[0-9]{0,3}\.[0-9]+/g)).replace(/,/g, "");
var result = parseFloat(foundStr).toFixed(2);