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 days ago.
Improve this question
The condition is that 5 digits must pass the test, but not the same ones in a row. For example, 12345, 223341,44441 must pass. But not 00000, 11111, etc.
The following expression should work for your given scenario:
const
areAllDigitsSame = (str) => /^(\d)\1+$/.exec(str) !== null,
isValid = (str) => !areAllDigitsSame(str);
// Valid
console.log(isValid('12345')); // true
console.log(isValid('223341')); // true
console.log(isValid('44441')); // true
// Invalid
console.log(isValid('00000')); // false
console.log(isValid('11111')); // false
You can invert the expression to eliminate the extra function, but you loose some meaning, and would have to add some documentation.
/**
* Checks if a string of digits does not contain all the same digit.
* #param {string} str - digit string to check
* #returns {boolean} true, if the string does not have all the same digit.
*/
const isValid = (str) => /^(\d)\1+$/.exec(str) === null;
// Valid
console.log(isValid('12345')); // true
console.log(isValid('223341')); // true
console.log(isValid('44441')); // true
// Invalid
console.log(isValid('00000')); // false
console.log(isValid('11111')); // false
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
I've created a function that returns the next number taking into account decimals, but am having an issue when the input number has a zero (0) proceeding the decimal.
const getNextValue = (input) => {
const newNumber = input
.toString()
.replace(/\d+$/, (number) =>
parseInt(number) +1)
return parseFloat(newNumber)
}
console.log(getNextValue(3.3)) // returns 3.4 as it should
console.log(getNextValue(3.34)) // returns 3.35 as it should
console.log(getNextValue(3.002)) // returns 3.3 as it ignores the zeros
You could skip the zeros:
const getNextValue = (input) => {
const newNumber = input
.toString()
.replace(/^\d+$|[1-9]+$/, (number) =>
parseInt(number) + 1);
return parseFloat(newNumber)
}
console.log(getNextValue(3.3)) // returns 3.4 as it should
console.log(getNextValue(3.34)) // returns 3.35 as it should
console.log(getNextValue(3.002)) // returns 3.003
console.log(getNextValue(30)) // returns 31
A completely different approach that should solve all the mentioned issues. I've added the character '1' in front of the decimal places to avoid the problem with leading zeros and to store the carry. At the end I add the carry and remove this character.
const getNextValue = (input) => {
const str = input.toString();
if (!str.includes('.')) return input + 1;
const numbers = str.split('.');
const dec = (+('1' + numbers[1]) + 1).toString();
return parseFloat(`${+numbers[0] + +dec[0] - 1}.${dec.substring(1)}`);
}
console.log(getNextValue(3.3)) // returns 3.4 as it should
console.log(getNextValue(3.34)) // returns 3.35 as it should
console.log(getNextValue(3.002)) // returns 3.003
console.log(getNextValue(3.9)) // returns 4
console.log(getNextValue(3.09)) // returns 3.1
console.log(getNextValue(30)) // returns 31
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 1 year ago.
Improve this question
Hello I use a javascript function to change my HTML background color by DI state
here's my code
function pageData() {
var DI1_STATE =document.getElementById('DI1').textContent; //load DI1
console.log(DI1_STATE); //DI1_STATE= ON or OFF(TYPEOF = String)
console.log(DI1_STATE=='ON'); //ALWAYS FLASE
console.log(DI1_STATE=='OFF'); //ALWAYS FLASE
var result = DI1_STATE.localeCompare('ON'); //WORK preset 1(TRUE) or -1(FLASE)
console.log(result);
if (DI1_STATE == 'ON'){
document.getElementById('DI1').style.backgroundColor = 'Coral';
document.getElementById('DI1').style.color = 'White';}
else{
document.getElementById('DI1').style.backgroundColor = '#ccc';
document.getElementById('DI1').style.color = 'black';}}
I wonder why == is not work
the whole Html code
I made the server at a microchip,i update the "DI1" by getsensorDATA3()
and the server command below
You always have to check for line breaks, spaces or other non visible characters when comparing string values from html elements. Try
var DI1_STATE =document.getElementById('DI1').textContent.trim()
localeCompare is used to determine sort order and only reports back if the reference string comes before or after the comparison string (in the sort order):
Negative when the referenceStr occurs before compareString
Positive when the referenceStr occurs after compareString
Returns 0 if they are equivalent
You might use it like array.sort((a, b) => b.localeCompare(a));
Tests....
let test = document.getElementsByTagName('textarea')[0].value;
console.log('"' + test + '"')
console.log('test == "TEST"', test == "TEST") // false
console.log('test.localeCompare("TEST")', test.localeCompare("TEST")) // 1
test = test.trim();
console.log('test == "TEST"', test == "TEST") // true
console.log('test.localeCompare("TEST")', test.localeCompare("TEST")) // 0
<textarea>TEST </textarea>
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
This post was edited and submitted for review 3 days ago.
Improve this question
Please check the code below first.
const plusFn = function(){
const sign = '+'
inputUser.textContent += sign
const equalFn = function(){
const input = `${inputUser.value}`
const numbers = input.split(`${sign}`)
const result = eval(`${+numbers[0]}${sign}${+numbers[1]}`)
}
btnEqual.addEventListener('click',equalFn)
}
btnPlus.addEventListener('click',plusFn)
Let's assume our user pressed 123 and wrote it to input area, then pressed +, from now on he trigerred the plusFn which determines a specific operator and adding a new event listener for equality button. When he gives second number and presses the equality button, operating will work as upside. Is it safe to use like that?
but I couldn't think any alternative
For something as simple as your example, where you have exactly two inputs and an operator from a constrained list (just + in your example, but I'm guessing you have three others), you could use a dispatcher object or Map:
const operatons = {
"+": (a, b) => a + b,
"*": (a, b) => a * b,
"/": (a, b) => a / b,
// ...
};
// Using it...
const operation = operation[operator];
if (!operation) {
throw new Error(`Invalid operator "${operator}"`);
}
const result = operation(input1, input2);
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 need to replace 02:04.887004 to 02:04.887 with jquery or js.
Other times I have microseconds just with four decimals (02:04.8348) and I would have 02:04.834
I would use regexp to find $:[d][d].$ and then return it but with the three decimals
If the length of the string is reliable, you can just trim the unwanted characters from the string, e.g.
let time = '02:04.887004';
// If format is reliable, get first 9 characters
console.log(time.substr(0,9));
// If length might vary and number of decimals is at least 3
// Trim from end
console.log(time.slice(0, -(time.length - time.indexOf('.') - 4)))
// Trim from start
console.log(time.substr(0, time.length - time.indexOf('.') + 2));
If the format is more unreliable, you have more work to do.
You can use a regular expression or a split function or a substring on the string to format your timestring. Here is an example of the three:
const time = '02:04.887004';
const regex = /[\d]{2}:[\d]{2}\.[\d]{3}/
const formatTime = time => {
const match = time.match(regex);
return match ? match[0] : match;
}
const formatTime2 = time => {
const m = time.split(':').shift();
const s = time.split(':').pop().split('.').shift();
const ms = time.split('.').pop().substr(0,3);
return m + ':' + s + '.' + ms;
}
const formatTime3 = time => {
return time.substr(0,9);
}
console.log(formatTime(time));
console.log(formatTime2(time));
console.log(formatTime3(time));
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 have an expression such as xsin(x) it is valid only if * comes between x and sin(x) and make it as x*sin(x)
my idea is first search for x then insert * between x and another variable if there is a variable.
equation
sin(x)cos(x) to sin(x)*cos(x)
pow((x),(2))sin(x)to pow((x),(2))*sin(x)
sin(x)cos(x)tan(x) to sin(x)*cos(x)*tan(x)
etc
I am trying with this code..
function cal(str)
{
//var string = "3*x+56";
var regex = /([a-z]+)\(\(([a-z]+)\),\(([0-9]+)\)\)\(([a-z0-9\*\+]+)\)([\*\-%\/+]*)/;
var replacement = "$1($2($4),($3))$5";
while(str.match(regex))
{
str = str.replace(regex,replacement);
}
return str;
}
This one matches right parentheses followed by a letter (e.g. )s ), and inserts a * (e.g. )*s )
It also replaces x followed by a letter with x* and that letter
It should work for x+sin(x) and xsin(x)
function addStars(str) {
return str.replace(/(\))([A-Za-z])/g,function(str, gr1, gr2) { return gr1 + "*" + gr2 }).replace(/x([A-Za-wy-z])/g,function(str, gr1) { return "x*" + gr1 })
}
document.write(addStars("x+sin(x)tan(x)ln(x)+xsin(x)"))
Help from:
JavaScript - string regex backreferences
qwertymk's answer
> 'sin(x)cos(x)'.replace(/(?!^)\w{3}/g, '*$&')
< "sin(x)*cos(x)"
> 'pow((x),(2))sin(x)'.replace(/(?!^)\w{3}/g, '*$&')
< "pow((x),(2))*sin(x)"
> 'sin(x)cos(x)tan(x)'.replace(/(?!^)\w{3}/g, '*$&')
< "sin(x)*cos(x)*tan(x)"
This says: replace anything that doesn't start at the beginning and has three letters with a * and everything that matched