I receive a string.
It should be in the format:
number,number
for example:
34.798,52.123
How can I verify that the number is in this format ? I need to assign it to some vars, and do some calculation. But since it is javascript (node.js), someone may submit a function instead and try to make my app invoke it. How do I verify that a submitted string is in the above format ?
I've considered the following approach:
function checkIfValid(input){
var result = false;
input = input.trim();
var tokens = input.split(",");
if(tokens.length==2){
if(!isNaN(tokens[0]&&!isNaN(tokens[1]){
result = true;
}
}
return result;
}
Is there a better way to do this ? Can it be hacked ?
check for invariance across parseFloat
function checkIfValid(input){
input = input.trim();
var tokens = input.split(",");
if(tokens.length === 2){
var t0 = tokens[0];
var t1 = tokens[1];
return parseFloat(t0) == t0 && parseFloat(t1) == t1;
}
return false;
}
You could use JSON.parse (after wrapping in [...]) and then check you got an array of two numbers:
var x = null;
try { x = JSON.parse("[" + data + "]"); } catch (err) { x = null; }
if (x && x.constructor === Array && x.length === 2 &&
typeof x[0] === "number" && typeof x[1] === "number") {
... data is ok ...
} else {
... data is invalid ...
}
this approach also scales to other more complex cases.
The only annoying thing is that certain valid numbers for Javascript are not valid for JSON (for reasons I don't understand). For example "1." is not valid JSON (a digit is mandatory after the decimal point). You also cannot use NaNs and infinity values because that's also invalid in JSON.
The problem with your code is the edge case of isNaN('') == false; this is because '' is converted into a numerical value of 0 which can be represented.
You should parse the values first using parseFloat():
function checkIfValid(input)
{
var parts = input.split(',');
return parts.length == 2 && parts.every(function(part) {
return !isNaN(parseFloat(part));
});
}
Related
I want to remove all numeric values from a string
But only if the string contains at least one letter.
How can I do this in JavaScript?
For e.g.
var s = "asd23asd"
Then result must be asdasd
However if
var s = "123123"
Then result must be 123123 as the string does not have any letters.
function filter(string){
var result = string.replace(/\d/g,'')
return result || string;
}
or directly
var newString = string.replace(/\d/g,'') || string;
Why || works
the || and & are conditionals operators and sure that you used in if, while ...
If you do somethin like
var c1 = false, c2 = true, c3= false, c4 = true;
if( c1 || c2 || c3 || c4) {
}
This evaluation will stop in the first moment that is valid or invalid.
this mind that the evaluation stop in c2 this mind that is more fast
(true || false) than (false || true)
At this point we can add another concept, the operator return always the last element in the evaluation
(false || 'hey' || true) return 'hey', remember in JS 'hey' is true but '' is false
Interesting examples:
var example = {
'value' : {
'sub_value' : 4
}
}
var test = example && example.value && example.value.sub_value;
console.log(test) //4
var test_2 = example && example.no_exist && example.no_exist.sub_value;
console.log(test_2) //undefined
var test_3 = example.valno_existue.sub_value; //exception
function test_function(value){
value = value || 4; //you can expecify default values
}
You can try this. First check if the word contains any alphabet, if yes then replace.
var s = "asd23asd";
if(/\w+/.test(s))
s = s.replace(/\d+/g, '');
([a-zA-Z]+)\d+|\d+(?=[a-zA-Z]+)
You can try this.Replace by $1.See demo.
https://regex101.com/r/nS2lT4/27
Javascript Code
var txt='asd23ASd3';
if(parseInt(txt))
var parsed=txt;
else
var parsed=txt.replace ( /[^a-zA-Z]/g, '');
console.log(parsed)
I know you can do ternary expressions in Javascript for an if - else statement, but how about an else- else if- else statement? I thought that surely this would be supported but I haven't been able to find any info about it and wasn't able to get it to work just hacking around.
In contrast to Robby Cornelissen's answer - there is no problems with readability if you format it properly (and not writing PHP, since it messed up the operator by making it left-associative in contrast to all other languages that have that construct):
var y =
x == 0 ? "zero" :
x == 1 ? "one" :
"other";
EDIT
What I was looking for is a shorter version of "if expression 1 is true, return expression 1. Else if expression 2 is true, return expression 2. Else return expression 3". Is there no clean way to do this?
There is: expression1 || expression2 || expression3. (It would have been nice if you had put this into your question in the first place.) This is commonly used for default values:
var defaults = null;
function hello(name) {
var displayName = name || (defaults && defaults.name) || "Anonymous";
console.log("Hello, " + displayName + ".");
}
hello("George");
// => Hello, George.
hello();
// => Hello, Anonymous.
defaults = {};
hello();
// => Hello, Anonymous.
defaults.name = "You"
hello();
// => Hello, You.
However, it is important to be aware of the conditions for truthiness. For example, if you expect "" or 0 to be a valid value that does not need to be replaced by a default, the code will fail; this trick only works when the set of possible non-default values is exactly the set of truthy values, no more and no less. E.g.
function increment(val, by) {
return val + (by || 1); // BUG
}
increment(10, 4);
// => 14
increment(10, 1);
// => 11
increment(10);
// => 11
increment(10, 0);
// => 11 <-- should be 10
In this case you need to be explicit:
function increment(val, by) {
return val + (typeof(by) === "undefined" ? 1 : by);
}
I wouldn't recommend it because of readability, but you could just nest ternary operators:
var y = (x == 0 ? "zero" : (x == 1 ? "one" : "other"));
This would be the equivalent of:
var y;
if (x == 0) {
y = "zero";
} else if (x == 1) {
y = "one";
} else {
y = "other";
}
You can extend a ternary condition if you're good. It gets to be messy though.
var number = 5;
var power = 2;
var ans = Math.pow(number,power);
var suggest = ( ans == 5 ? 5 : ans == 10 ? 10 : ans == 15 ? 15 : ans == 25 ? "works" : null);
console.log(suggest);
I may have added to many because I'm on my phone haha but try it in your developer panel.
I have a table which has a couple cells that contain simple numbers (IE: 1.00, 1000.00, 10000.00). I'm trying to format the cell contents using the 'format' function below. I have had success with this function in a different area of my code, but for whatever reason (the reason why I'm here) when I try to feed the contents of the table cells in, it doesn't work as I expected.
The problem is that the typeof my cell contents is 'object' and not 'number', so it skates right by the if statement and just returns my original value back to me. Is there a way I can coerce the data to be typeof number? I thought var n = new Number(cellText); would do the trick, however, the typeof comes back as object. Confused.
In globalize.js:
Globalize.format = function( value, format, cultureSelector ) {
culture = this.findClosestCulture( cultureSelector );
if ( value instanceof Date ) {
value = formatDate( value, format, culture );
}
else if ( typeof value === "number" ) {
value = formatNumber( value, format, culture );
}
return value;
};
In my page:
$(document).ready(function () {
$('td[globalize="true"]').each(function () {
var $this = $(this);
var cellText = $this.text();
if (cellText != null) {
var n = new Number(cellText);
var v = Globalize.formatNumber(n, _gloNum[0]);
$this.text(v);
}
})
});
The problem is that the typeof my cell contents is 'object' and not
'number'
When you do:
new Number
You are creating new instance of Number object, that's why it gives you object and not number.
Is there a way I can coerce the data to be typeof number?
var n = +(cellText);
Or
var n = Number(cellText);
In JavaScript new Number returns a Number object. Have a look at parseFloat or parseInt.
Change:
var n = new Number(cellText);
To
var n = Number(cellText);
Or
var n = parseFloat(cellText);
Or
var n = parseInt(cellText, 10);
Depending on what you need.
new Number(cellText) returns a Number object, not a number primitive.
Use parseInt or parseFloat instead.
var cellText = '12.34',
a = new Number(cellText), // 12.34, but a Number object
b = parseInt(cellText, 10), // 12
c = parseFloat(cellText); // 12.34
typeof a; // 'object'
a instanceof Number; // true
typeof b; // 'number'
typeof c; // 'number'
The typeof is buggy in JavaScript. I suggest you use the following function instead:
function typeOf(value) {
if (value === null) return "null";
else if (typeof value === "undefined") return "undefined";
else return Object.prototype.toString.call(value).slice(8, -1);
}
Is there a JavaScript equivalent to .NET's String.IsNullOrWhitespace so that I can check if a textbox on the client-side has any visible text in it?
I'd rather do this on the client-side first than post back the textbox value and rely only on server-side validation, even though I will do that as well.
For a succinct modern cross-browser implementation, just do:
function isNullOrWhitespace( input ) {
return !input || !input.trim();
}
Here's the jsFiddle. Notes below.
The currently accepted answer can be simplified to:
function isNullOrWhitespace( input ) {
return (typeof input === 'undefined' || input == null)
|| input.replace(/\s/g, '').length < 1;
}
And leveraging falsiness, even further to:
function isNullOrWhitespace( input ) {
return !input || input.replace(/\s/g, '').length < 1;
}
trim() is available in all recent browsers, so we can optionally drop the regex:
function isNullOrWhitespace( input ) {
return !input || input.trim().length < 1;
}
And add a little more falsiness to the mix, yielding the final (simplified) version:
function isNullOrWhitespace( input ) {
return !input || !input.trim();
}
It's easy enough to roll your own:
function isNullOrWhitespace( input ) {
if (typeof input === 'undefined' || input == null) return true;
return input.replace(/\s/g, '').length < 1;
}
no, but you could write one
function isNullOrWhitespace( str )
{
// Does the string not contain at least 1 non-whitespace character?
return !/\S/.test( str );
}
Try this out
Checks the string if undefined, null, not typeof string, empty or space(s
/**
* Checks the string if undefined, null, not typeof string, empty or space(s)
* #param {any} str string to be evaluated
* #returns {boolean} the evaluated result
*/
function isStringNullOrWhiteSpace(str) {
return str === undefined || str === null
|| typeof str !== 'string'
|| str.match(/^ *$/) !== null;
}
You can use it like this
isStringNullOrWhiteSpace('Your String');
You must write your own:
function isNullOrWhitespace(strToCheck) {
var whitespaceChars = "\s";
return (strToCheck === null || whitespaceChars.indexOf(strToCheck) != -1);
}
trim() is a useful string-function that JS is missing..
Add it:
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g,"") }
Then: if (document.form.field.value.trim() == "")
Pulling the relevant parts of the two best answers, you get something like this:
function IsNullOrWhitespace(input) {
if (typeof input === 'undefined' || input == null) return true;
return !/\S/.test(input); // Does it fail to find a non-whitespace character?
}
The rest of this answer is only for those interested in the performance differences between this answer and Dexter's answer. Both will produce the same results, but this code is slightly faster.
On my computer, using a QUnit test over the following code:
var count = 100000;
var start = performance.now();
var str = "This is a test string.";
for (var i = 0; i < count; ++i) {
IsNullOrWhitespace(null);
IsNullOrWhitespace(str);
}
var end = performance.now();
var elapsed = end - start;
assert.ok(true, "" + count + " runs of IsNullOrWhitespace() took: " + elapsed + " milliseconds.");
The results were:
RegExp.replace method = 33 - 37 milliseconds
RegExp.test method = 11 - 14 milliseconds
You can use the regex /\S/ to test if a field is whitespace, and combine that with a null check.
Ex:
if(textBoxVal === null || textBoxVal.match(/\S/)){
// field is invalid (empty or spaces)
}
a script returns either a number like 0.0580 so in x.xxxx format or a (x) for X units left.
I want to format the number 0.0580 and return 5.8 cent or return x units left.
Any ideas how to do that in javascript? Especially how do I format the x.xxxx?
In case the first x is not 0 I want to return e.g. 1.75$.
MS has written a nice plugin for jquery. it's especially useful if you're localizing. Give it a go:
http://weblogs.asp.net/scottgu/archive/2010/06/10/jquery-globalization-plugin-from-microsoft.aspx
I'm not sure if this can be used outside of jquery...
I may be spoiling you here, but whatever. Here's a function that I found somewhere at some point and have been recycling since. I haven't actually bothered to look much into it to figure out what it does exactly, but it has been rather useful:
function FormatMoneyAmount(starting_string, ending_string) {
//check validity of input (true = invalid, false = valid)
var valid_exp = new RegExp ('[^0-9,.$]', 'gi');
input_invalid = (typeof(ending_string) == 'undefined' && valid_exp.test(starting_string));
//check if more than 2 digits follow decimal or no decimal
decimal_invalid = typeof(ending_string) == 'undefined' && (starting_string.indexOf('.') > -1) && ((starting_string.length - starting_string.indexOf('.')) > 3);
if (input_invalid || decimal_invalid) {
ending_string = starting_string;
} else {
//remove commas, dollar signs
var replace_exp = new RegExp ('[,$]', 'gi');
starting_string = starting_string.replace(replace_exp, '');
//remove decimal if ending string not set, save for adding on later
var decimal_substring = '';
if (typeof(ending_string) == 'undefined' && starting_string.indexOf('.') > -1) {
decimal_substring = starting_string.substring(starting_string.indexOf('.'), starting_string.length);
remaining_string = starting_string.substring(0,starting_string.indexOf('.'));
} else {
remaining_string = starting_string;
}
//if string is already 3 characters or less, do nothing
if (remaining_string.length > 3) {
//separate last 3 characters of string from rest of string
var final_three = remaining_string.substring(remaining_string.length - 3, remaining_string.length);
remaining_string = remaining_string.substring(0, remaining_string.length - 3);
//if not first group of 3, add new group before old group with comma, else set to new group
ending_string = (typeof(ending_string) == 'undefined') ? final_three + ((typeof(decimal_substring) == 'undefined') ? '' : decimal_substring) : final_three + ',' + ending_string;
//call function again if more than 3 digits remaining to process, else add to end string
if (remaining_string.length > 3) {
ending_string = FormatMoneyAmount(remaining_string, ending_string);
} else {
ending_string = remaining_string + ',' + ending_string;
}
} else {
ending_string = (typeof(ending_string) == 'undefined') ? remaining_string : remaining_string + ',' + ending_string + ((typeof(decimal_substring) == 'undefined') ? '' : decimal_substring);
}
}
return ending_string;
}
The first thing to do is check the format of the string, since you will have two code paths depending on the result:
if (typeof num = "string" && num.slice(0,1) == "(" && num.slice(-1) == ")") {
// String is in the format (x), so we just need to return that number
return num.slice(1,-1) + " units left";
}
The next part is to check if the number is less than 1, indicating that it is cents and not whole dollars. If it is less than 1, multiplying it by 100 will give you the number of cents you're after:
if (+num < 1)
// 0.0580 * 100 = 5.8
return (num * 100) + " cents";
else
return +num + "$";