I have a large number of text fields that need to be evaluated onkeyup to be sure nothing is entered but numbers. Decimals are ok. So is the absence of a value.
For some reason this is matching on decimals. Eg I type 4 and then . and it flags on .
How do I correct this?
var s_in = 0;
for (var i = 10; i < 19; i++) {
var fObj = document.getElementById(field+'_'+i);
var text = fObj.value;
if (text) {
var s = parseInt(text);
var pattern = /^[+-]?(\d*\.)?\d+$/;
var result;
if ((result = pattern.exec(text)) != null) {
if (s > -1) {
s_in += s;
}
} else { // not empty and not a number
alert('The entry for Hole ' + i + ' ' + ucfirst(field) + ' is "' + text + '" This is not a number. It will be erased now.');
fObj.value = '';
fObj.focus();
return false;
}
}
}
Your regex requires one or more digits after the decimal point and you have to escape the - in the first group). If you don't want to require a digit after the decimal, then you can use this (changes a + to a * and puts \ in front of the -):
/^[+\-]?(\d*\.)?\d*$/
Related
So I need a tiny bit of help with this code, Some background information: The user inputs a number, the code takes the number and outputs various combinations of numbers that multiply to it.
For example:
Input: 7
Output: (1,7)(7,1).
*But what really happens:
*
Input: 7
Output: (7,1)
I want my code to reverse the numbers as well, so it makes can look like it has two combinations
var input= parseInt(prompt("Please enter a number larger than 1"));
var arr = [];
if(input <= 1) {
console.log("Goodbye!")
}
while(input > 0) {
var arr = [];
var input = parseInt(prompt("Please enter a number larger than 1"));
for (var i = 0; i < input; ++input) {
var r = ((input / i) % 1 === 0) ? (input / i) : Infinity
if(isFinite(r)) {
arr.unshift(r + ", " + i)
}
}
console.log("The multiplicative combination(s) are: " + "(" + arr.join("), (") + "). ");
}
My code just need this tiny bit of problem fixed and the rest will be fine!
Your code has 2 infinite loop because you never change i and always increase input.
also in this line for (var i = 0; i < input; ++input) you never let i to be equal to the input so in your example (input=7) you can not have (7,1) as one of your answers. I think this is what you looking for:
var input = 1;
while(input > 0) {
input = parseInt(prompt("Please enter a number larger than 1"));
if(input > 1) {
var arr = [];
for (var i = 0; i <= input; ++i) {
var r = ((input / i) % 1 === 0) ? (input / i) : Infinity
if(isFinite(r)) {
arr.unshift(r + ", " + i)
}
}
console.log("The multiplicative combination(s) are: " + "(" + arr.join("), (") + "). ");
continue;
}
else{
console.log("Goodbye!");
break;
}
}
Need help on why my recursion program in javascript is not working. It is supposed to take the words from the text file and display the number of words, lines and characters in it. Please help me modify my code or tell me where my mistake is because I do not know where. Here is the javascript code:
var fs = require("fs");
var text = fs.readFileSync("text.txt", "utf8");
function countLines(text) {
if (text == "") {
return 0;
} else {
return 1 + countLines(text.substring(text.indexOf("\n") + 1));
}
}
function countWords(text) {
if (text == "") {
return 0;
} else {
return 1 + countWords(text.substring(text.indexOf(" ") + 1));
}
}
function countCharacters(text) {
if (text == "") {
return 0;
} else {
return 1 + countCharacters(text.substring(1));
}
}
var lineCount = countLines(text);
var wordCount = countWords(text);
var characterCount = countCharacters(text);
console.log(
"There are " +
lineCount +
" lines, " +
wordCount +
" words, and " +
characterCount +
" characters in the file."
);
This is the text.txt file:
I was running to the zoo.
If we are counting lines, the base case is not if (text == ""), it is when no \n is found in text. Changing the base case can result in a new way to think about the problem and a simplification of our code.
Given i is the position of \n in the string text -
If i is less than zero, text is the last line. Return 1.
(inductive) i is 0 or greater, text has more than one line. Return 1 plus the result of the sub-problem.
function countLines(text) {
const i = text.indexOf("\n")
if (i < 0) return 1 // 1
else return 1 + countLines(text.substring(i + 1)) // 2
}
console.log(countLines(`Hello`))
console.log(countLines(`Hello
World,`))
console.log(countLines(`Hello
World,
We don't deserve you.`))
We could be less verbose with a ternary expression -
function countLines(text) {
const i = text.indexOf("\n")
return (i < 0) ? 1 : 1 + countLines(text.substring(i + 1))
}
Your issue is blindly recursing without checking the result of indexOf, which is -1 when the target isn't found
so
text.substring(text.indexOf(" ") + 1)
becomes
text.substring(-1 + 1)
in other words
text.substring(0)
So, you infinitely recurse the last word (and line, for that matter)
If .indexOf returns -1, you should return 1
Note: I removed the unnecessary else in your code - no need for else when the if returns a value - this make for cleaner code (in my opinion, you're welcome to use else if you must
I've shown two different ways to test indexOf
var text = "I was running to the zoo.";
function countLines(text) {
if (text == "") {
return 0;
}
const index = text.indexOf("\n");
if (index < 0) {
return 1;
}
return 1 + countLines(text.substring(index + 1));
}
function countWords(text) {
if (text == "") {
return 0;
}
const index = text.indexOf(" ") + 1;
if (index) { // since we've added 1, a "not found" -1 would be 0 here, and be falsey
return 1 + countWords(text.substring(index));
}
return 1;
}
function countCharacters(text) {
if (text == "") {
return 0;
}
return 1 + countCharacters(text.substring(1));
}
var lineCount = countLines(text);
var wordCount = countWords(text);
var characterCount = countCharacters(text);
console.log(
"There are " +
lineCount +
" lines, " +
wordCount +
" words, and " +
characterCount +
" characters in the file."
);
i am making a basic system to replace some characters.
Example:
\t - Replace for tab-size 4
\n - Replace for
this working very good, but, when is replaced a hex code (In this case the format is: {FFFFFF}) not work if the code is on pos 1 or more. Only work if the code is in first pos of string of the textarea
code =
$(document).ready(function()
{
$('#dialog_edit_input').keyup(function()
{
var val = $(this).val();
var start = -1, end = -1;
// Backspaces (\t, \n)
val = val.replace(/\\n/g, "<br />");
val = val.replace(/\\t/g, "<p class=\"create_t\"></p>");
// Extraer colores hex PAWN
start = val.search("{");
end = val.indexOf("}", (start != -1 ? start+6 : 0));
var is_posible = ((start != -1 && end != -1) && end == start + 7);
var _color_real = is_posible ? val.substr(start, end+1) : null;
var _color = _color_real != null ? _color_real.substr(1, _color_real.length-2) : null;
if(is_posible)
val = val.replace(_color_real, "<span style=\"color: #" + _color + "\">");
console.log(end);
$('#agregar_resultado').html(val);
});
});
You can use a regular expression like you did for the other substitutions:
val = val.replace(/\{([0-9A-Fa-f]{6})\}/g, '<span style="color: #$1">');
Notes:
The parentheses in the regular expression create a group. That means the six hex digits will form the first (and only) group. Notice that the braces are not within the parentheses. They are necessary for a match to take place, but they are not part of the group.
The $1 in the substitution string will be replaced with the value of the first matched group, which in this case is the six hex digits.
jsfiddle
As for why your code is not working as written, you are looking for only one occurrence. Instead, you would need to have a loop.
var pos = 0;
while (pos < val.length) {
var start = val.indexOf('{', pos);
if ((start >= 0) && ((start + 7) < val.length)) {
if (val.charAt(start + 7) == '}') {
var color = val.slice(start + 1, start + 7);
var replacement = '<span style="color: #' + color + '">';
val = val.slice(0, start) + replacement + val.slice(start + 8);
pos = start + replacement.length;
} else {
pos = start + 1;
}
} else {
pos = val.length;
}
}
jsfiddle
I am using java script to print a 10 digit number. example 1234567891. But i want that number to be printed in a particular format link 123.456.789-1. Can somebody please help me to sort this.
Very simple way to do it:
var num = "1234567891";
var formattedNum = formatNum(num);
console.log(formattedNum); //returns 123.456.789-1
function formatNum(num) {
var arr = num.split('');
var output = '';
for (var i = 0; i < arr.length; i++) {
output += arr[i];
if (i === 2 || i === 5) output += '.';
if (i === 8) output += '-';
}
return output;
}
First, convert to a string with leading zeroes,
then insert the punctuation as you desire.
function formatnum(n) {
n = ("0000000000" + n).substr(-10); // take the last 10 digits of the padded string
return ( n.substr(0,3) + "." + n.substr(3,3) + "." + n.substr(6,3) + "-" + n.substr(9,1) );
}
The output of this code separates each 4 digits by a hyphen(-) with the regex \w, but it doesn't work if I replace \w to other regular expressions. Why is that?
This one works perfectly.
function gen(length, separator) {
var license = new Array(length + 1).join((Math.random().toString(36) + '00000000000000000').slice(2, 18)).slice(0, length);
return license.toUpperCase().replace(/(\w{4})/g, '$1' + separator).substr(0, length + Math.round(length/4)-1);
}
document.write(gen(16, '-'));
This one does not separates by a hyphen each 4 digits.
function gen(length, separator) {
var license = new Array(length + 1).join((Math.random().toString(36) + '00000000000000000').slice(2, 18)).slice(0, length);
return license.toUpperCase().replace(/([A-Z]{4})/g, '$1' + separator).substr(0, length + Math.round(length/4)-1);
}
document.write(gen(16, '-'));
I think you need something like this:
function gen(length, separator) {
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var text = '';
for( var i=0; i < length; i++ ) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
if(i%4 == 3 && i<length-1) text += separator;
}
return text;
}
document.write(gen(16, '-'));