Add blank spaces in a string after some random digits [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'm trying to add spaces to my input value while the user typing, it works for the constant digits like after 4 letters or after 5 letters. But I couldn't manage to add space after certain digits dynamically.
for example
if user types 1234567890
blocks: [3,3,4]
expected output: 123 456 7890
if user types 1234567890
blocks: [3,2,2,3]
expected output is: 123 45 67 890

Handling inputs as the user types can be tricky.
Although not perfect, one solution is to calculate what the expected result should be, and then compare with what it currently is. If they are different then update the actual input with the calculated one.
Below is a simple example,.. It will even handle were the user pastes in the numbers.
One issue with the below is the cursor position if say you inserted the number mid way, but this could be maybe handled with remembering the cursor position and restoring.
const splits = [3,3,4];
$('#a').on("input", function(){
let count = 0;
const breaks = splits.map(m => { const ret = m + count; count += m; return ret; });
const a = this.value.split("").filter(f => f !== ' ');
const s = a.map((m, ix) => {
if (breaks.includes(ix + 1)) return m + " "
else return m;
}).join("");
if (this.value.trim() !== s.trim()) this.value = s;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="a"/>

Try the below code
function splitValue(value, index) {
return value.substring(0, index) + " " + value.substring(index);
}
var test=[3,3,4];
var secondVar = '';
var firstVar = '1234567890';
for(let i = 0; i < test.length; i++){
var TestVar = splitValue(firstVar, test[i]);
secondVar = secondVar + " " + TestVar.split(" ")[0];
secondVar=secondVar.trim();
if(i == 0)
firstVar = firstVar.replace(secondVar.trim(),'');
else
firstVar = firstVar.replace(secondVar.split(' ')[i + 1],'');
}
console.log(secondVar);

Related

Find highest number of decimal places in String [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 2 years ago.
Improve this question
The example string(s) can look like that:
"3.0000+3"
"3.00+3.00"
"3.00+3.000"
I want to find the highest amount of decimal places out of the numbers inside 1 string
The most straight-forward way to do this is iterating over the string, checking for the occurence of a dot and from there on count the number of digits up to the next character that's NOT a number or the end of the string. Since your string contains multiple numbers you need to add a variable which holds the highest amount of decimal places.
e.g.
var str = "3.00+3.000";
function getDecimalPlaces(numb) {
var highest = 0;
var counter = 0;
for (a = 0; a < numb.length; a++) {
if (numb.charAt(a - 1) == ".") {
do {
counter++;
a++;
}
while (!isNaN(numb.charAt(a)) && a < numb.length);
}
if (counter > highest) {
highest = counter;
}
counter = 0;
}
return highest;
}
console.log(str + " has " + getDecimalPlaces(str) + " decimal places");
This can be made a bit more elegant by using a regular expression in conjunction with the .match() method. This searches a string for a given pattern and returns an array of results.
var str = "3.00+3.000";
console.log(str.match(/(\.)([0-9]+)/g));
This will return an array like:
[".00", ".000"]
By comparing the length of it's elements - minus 1 since it includes the dot - we can get the number of decimal places using this nifty short function:
var str = "3.00+3.000";
var highest = str.match(/(\.)([0-9]+)/g).reduce(function(a, b) {
return Math.max(a.length - 1, b.length - 1);
});
console.log(str + " has " + highest + " decimal places");

Translate a Javascript function to Python [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'am newbie in Python and i'am having a hard time trying to translate this Javascript arrow function into Python. I'am not able to make the part where i use substring in JS to get the next 3 values in my loop when i find '\x1D'. Any tips or suggestions ?
module.exports = edi => {
let decompressedEdi = ''
let lastCompressor = 0
for (let i = 0; i <= edi.length; i++) {
if (edi[i] === '\x1D') {
let decimal = parseInt(edi.substring(i + 1, i + 3), 16)
let repeater = edi[i + 3]
decompressedEdi +=
edi.substring(lastCompressor, i) + repeater.repeat(decimal)
lastCompressor = i + 4
}
}
decompressedEdi += edi.substring(lastCompressor, edi.length)
return decompressedEdi.replace(/(\r\n|\n|\r)/gm, '')
}
In python, strings can be sliced like arrays :
for i, c in enumerate(edi):
if c == '\x1D':
decimal = int(edi[i+1:i+3], 16)
The int function has the following signature: int(str, base)
from re import sub
def decompress(edi):
decompressed = ""
last_compressor = 0
for i, c in enumerate(edi):
if c == "\x1D":
repetitions = int(edi[i + 1: i + 3], 16)
repeating_char = edi[i + 3]
decompressed += edi[last_compressor:i] + repeating_char * repetitions
last_compressor = i + 4
decompressed += edi[last_compressor:-1]
return sub("\r\n|\n|\r", decompressed)
How I read the code
Feel free to ignore this bit, but it might help.
Given edi which has a len, for each edi that matches \x1D, get the substring of edi from the index + 1 to index + 3 as a hexadecimal integer as set as decimal. The repeater is the index + 3'th element of edi for each element and it is expected to be a str. It will be repeated the hexadecimal number of times defined in decimal, but only after the substring of edi from lastCompressor to the current index. On each iteration where \x1D is matched, the lastCompressor is increased by 4.

Javascript Number to Roman Conversion [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 6 years ago.
Improve this question
I was looking to convert from Number to Roman (X, IV etc).
Someone proposed this solution, I'm going through the solution but I wasn't able to understand even though I debugged it.
Can someone explain what's going on? I'm just trying to learn some JS.
function convertToRoman(num) {
var roman = {"M" :1000, "CM":900, "D":500, "CD":400, "C":100, "XC":90, "L":50, "XL":40, "X":10, "IX":9, "V":5, "IV":4, "I":1};
str = "";
for (var i in roman ) {
var q = Math.floor(num / roman[i]); //Why?
num -= q * roman[i]; //Why?
str += i.repeat(q); //Why?
}
return str;
}
Description
Code described in comments below.
// this is a function declaration
// with a parameter called num
function convertToRoman(num) {
// this is an object, being used as a lookup
var roman = {"M" :1000, "CM":900, "D":500, "CD":400, "C":100, "XC":90, "L":50, "XL":40, "X":10, "IX":9, "V":5, "IV":4, "I":1};
console.log('num = ' + num);
// this is a variable of type string
str = "";
// for loop to go over each item in roman
for (var i in roman ) {
console.log('i = ' + i);
// calculates the Math Floor of the number passed in divided by the roman value
// this will do the number passed divided by 1000 first
// Example: convertToRoman(1201)
// Math.floor(1201 / 1000) = 1
var q = Math.floor(num / roman[i]); //Why?
console.log('q = ' + q);
// remove the value of q multiplied by roman[i]
// Example: convertToRoman(1201)
// q = 1
// num = num - 1 * 1000;
// this makes it so that num is less the roman symbol we just found
num -= q * roman[i]; //Why?
console.log('num = ' + num);
// this is to make the roman number string
// Example: num = 1201
// i = 1000
// q = 1
// str = str + "M";
// or
// num = 3102
// i = 1000
// q = 3
// str = str + "M" [repeated 3 times]
// str = 'MMM' at the end of this
str += i.repeat(q); //Why?
console.log('str = ' + str);
}
// return the string
return str;
}
console.log(convertToRoman(1201));
The var roman is an associative array with key being a string and value the decimal system value.
It's ordered descending in value.
The loop iterates the array calculating the max times each value at index is contained within the given number, and subtracting it from the number so that the new iteration can continue calculating the "rest"

How to convert two integer values into a floating number in javascript? [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 6 years ago.
Improve this question
So here is the scenario, I have two values:
var a=1
var b=23
I want a value like (a.b) 1.23:
var a=10
var b=45
I want a value like (a.b) 10.45
Is it possible? Then how?
var a=10; var b=45;
var result = +(a + '.' + b);
+ operator is unary operator for converting a string into a number.
See Mozilla Developer Network.
var a = 10;
var b = 45;
var res = a + (b/100);
Combine them into a string, and then run the result through parseFloat:
var a=1
var b=23
var result = parseFloat(a + "." + b);
Edit: As per #Vostrugin's comment, you can ensure the number of decimal places using toFixed()
parseFloat('0.0').toFixed(2) // this will give you 0.00
var a = 1;
var b = 2;
var c = a + "." + b;
alert(c);
The easiest way to do this is through string concatenation.
It would look like +(a + "." + b)
In JavaScript, a string added to a number becomes a string. A number appended to a string, and the string remains.
However, then we need to convert it to a number. We do that by either using parseInt, or +
Here is an example you can try for yourself
var n1 = document.getElementById("n1");
var n2 = document.getElementById("n2");
var result = document.getElementById("result");
function convertNumber() {
result.innerHTML = (+(n1.value + "." + n2.value));
}
#number-converter {
margin-top: 10px;
}
Number 1: <input type="text" id="n1" />
Number 2: <input type="text" id="n2" />
<button id="number-converter" onclick="convertNumber()">Calculate Number</button>
<p id="result"></p>
var test=function(a,b){
return parseFloat(a + "." + (b>10||b===0?b:(b+"5"))).toFixed(2);
};
console.log(test(1,23));
console.log(test(10,4));
console.log(test(0,0));
//That will always work
//THATS IF YOU WANT THE 10.45 ROUND EFFECT THAT YOU QUEST

Function is undefined in console log? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
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.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I am trying to create a tool to convert temperature values from Celsius, Fahrenheit, or Kelvin but the console says the function getTemperature() is undefined?
function getTemperature() {
var fahrenheit = document.formBox.tempF.value;
var celsius = document.formBox.tempC.value;
var kelvin = document.formBox.tempK.value;
var select = document.formBox.select.value;
//User gives initial temperature in fahrenheit, convert to C and K
if (select === "GivenF") {
var c = (5/9)*(fahrenheit-32);
var k = ((((fahrenheit-32)*5)/9) + 273.15);
document.getElementById("celsius").innerHTML = "This equals " + c " degrees celsius.";
document.getElementById("kelvin").innerHTML = "This equals " + k " kelvin.";
document.getElementById("fahrenheit").innerHTML = "";
}
//User gives initial temperature in celsius, convert to F and K
else if (select === "GivenC") {
var f = ((9/5)*celsius)+32;
var k = celsius+273.15;
document.getElementById("celsius").innerHTML = "";
document.getElementById("kelvin").innerHTML = "This equals " + k " kelvin.";
document.getElementById("fahrenheit").innerHTML = "This equals " + f " fahrenheit.";
}
//Use gives initial temperature in kelvin, convert to F and C
else if (select === "GivenK") {
var f = (9/5)*(kelvin-273)+32;
var c = kelvin-273.15;
document.getElementById("celsius").innerHTML = "This equals " + c " degrees celsius.";
document.getElementById("kelvin").innerHTML = "";
document.getElementById("fahrenheit").innerHTML = "This equals " + f " fahrenheit.";
};
}
There are syntax errors like
... = "This equals " + c " degrees celsius.";
where you miss + sign after variable.
It may be something with the way you call the function also, but syntax erros are in the first place.

Categories