Javascript array not working ?? confused - javascript

Anybody got any clue why this won't work with more than 1 date...
it only takes the first date in the array...
var unavailableDates = ["10-6-2011","13-6-2011"];
function unavailable(date) {
dmy = date.getDate() + "-" + (date.getMonth() + 1) + "-" + date.getFullYear();
if ($.inArray(dmy, unavailableDates) == 0) {
return [false, "", "Unavailable"];
} else {
var day = date.getDay();
return [(day != 0 && day != 2 && day != 3 && day != 4 && day != 6)];
}
}
see full example below
http://offline.raileisure.com/lee.php
Thanks in advance
Lee

It doesn't work because you're interpreting the return value of "$.inArray()" incorrectly. The function returns -1 when the search target cannot be found, and the index in the array when it can. Thus, when it returns 0, that means it did find what the code was looking for.
A cute trick — for those who like cute tricks — for checking the return value from functions like "$.inArray()" is to apply the "~" operator:
if (~$.inArray(needle, haystack)) {
// found it
}
else {
// did not find it
}
The "~" operator forms the bitwise complement (or "1's complement") of its argument. Because "~-1" is 0, and "~n" is non-zero for any other integer, it effectively converts the return value to a "truthy/falsy" value appropriately. Don't use it if you don't like cute tricks :-)
Also, that "dmy" variable used in a couple functions should be declared in each one with the var keyword.

jQuery.inArray returns the index of the item found, ie, when it matches the second value, it is returning 1, not the 0 you test for.
You should change your test to be >= 0 rather than == 0 when you do
if ($.inArray(dmy, unavailableDates) == 0) { ...

Is it reading it in as mm-dd-yyyy?
If so - then 13-6-2011 would not be a valid date.
Edit Okay - looking at your page; clearly not since 10th June is not available as expected.
I deleted the answer but where dates are concerned I think this is a valuable thing to remember (e.g. on a US client presumably I'd be right?) so I undeleted it.
I'll get rid of it again though if the community feels I should.

Try this:
in pure javascript:
I made ​​some modifications to make your code faster
function inArrayOrStr (o, v) {
return ~o.indexOf(v);
}
unavailableDates = ["10-6-2011","13-6-2011"];
function unavailable(date) {
var dmy = [date.getDate() ,(date.getMonth() + 1) , date.getFullYear()].join("-");
if (inArrayOrStr(unavailableDates, dmy) {
return [false, "", "Unavailable"];
} else {
var day = date.getDay();
return [day > 7];
}
}

Related

typescript 1+1 = 11 not 2

I have a TypeScript class without any import statement at the top. When I new calculateDate() and execute addMonth(new Date(), 1), it adds 11 months to today instead of 2. The m variable is always a result of string concatenation, instead of math addition operation. I even tried parseInt() with the string form of the two operands, it still performs string concatenation. Please help. Thanks.
export class calculateDate {
addMonth(thisDate:Date, monthCount:number){
if (thisDate && monthCount && monthCount != -1) {
let m : number = thisDate.getMonth() + monthCount;
console.log('m=', m);
let newDate: Date = new Date(thisDate.setMonth(m));
return newDate;
}
else
return null;
}
}
You are adding up two strings, try to parse them as int or use this syntax +thisDate.getMonth() + (+monthCount)

How to add a character to a string only if there aren't any of the same character?

I'm trying to make a function that checks whether a string has a period in it or not, then if it does not have a period, add one. I can only make it either add infinite periods or not add any at all.
function point() {
if (numberOne.indexOf(".") >= 0) {
numberOne = numberOne + addPoint;
document.getElementById("output").innerHTML = numberOne;
}}
You probably want == -1 depending on what indexOf returns when there is no match in your language
Right now you say:
If there is a period in this variable
Then add a period to this variable
update the element.
You want to say:
if I DON'T find a "."
then add a "."
checking indexOf == -1 or < 0 should achieve this.
point function should be like this,
function point() {
if (numberOne.indexOf(".") == -1) {
numberOne = numberOne + addPoint;
document.getElementById("output").innerHTML = numberOne;
}
}
indexOf returns -1 if not found. That's why you should compare with -1. that means period not found.
function point() {
if (numberOne.indexOf(".") == -1) {
numberOne = numberOne + addPoint;
document.getElementById("output").innerHTML = numberOne;
}
}

Checking if any given string is a valid date

Does anyone know of any way to check if strings are valid dates? I'm trying to block against invalid dates, while not forcing any kind of date format. Basically here's the problem:
!!Date.parse('hello 1') === true
Javascript can figure out a date from that string, therefore, it's a date. I'd rather it not be. Anyone?
How close would stripping out spaces around words get you? It at least weeds out "hello 1" and such.
Date.parse('hello 1'.replace(/\s*([a-z]+)\s*/i, "$1")); // NaN
Date.parse('jan 1'.replace(/\s*([a-z]+)\s*/i, "$1")); // Valid
[update]
Ok, so we'll just replace any non-alphanumerics that fall between a letter and a number:
replace(/([a-z])\W+(\d)/ig, "$1$2")
Since you're using moment.js, try using parsingFlags():
var m = moment("hello 1", ["YYYY/MM/DD"]).parsingFlags();
if (!m.score && !m.empty) {
// valid
}
It's the metrics used for isValid() and you can use them to make a stricter validation function.
Note: You can specify the other formats to support in the second argument's array.
Some other properties returned by parsingFlags() that might be of interest are the following:
m.unusedInput - Ex. ["hello "]
m.unusedTokens - Ex. ["MM", "DD"]
Use this function to check date
function isDate(s)
{
if (s.search(/^\d{1,2}[\/|\-|\.|_]\d{1,2}[\/|\-|\.|_]\d{4}/g) != 0)
return false;
s = s.replace(/[\-|\.|_]/g, "/");
var dt = new Date(Date.parse(s));
var arrDateParts = s.split("/");
return (
dt.getMonth() == arrDateParts[0]-1 &&
dt.getDate() == arrDateParts[1] &&
dt.getFullYear() == arrDateParts[2]
);
}
console.log(isDate("abc 1")); // Will give false
Working Fiddle
It would be ok if you check for several types of dates?
kind of this for narrow the permited dates:
if( givenDate.match(/\d\d\/\d\d\/\d\d\d\d/)
|| givenDate.match(/\w*? \d{1,2} \d{4}/)
|| givenDate.match(anotherFormatToMatch) )
UPDATED
Or, althougt it restrict characters, you coud use something like this:
function myFunction() {
var str = "The rain in SPAIN stays mainly in the plain";
var date = new Date(str);
if (date != "Invalid Date" && !isNaN(new Date(date) && !str.match(/a-z/g) )
alert(date);
}

javascript regexp, validating date problem

I have some code for validating date below:
function validateForm() {
var errFound = 0;
//var patt_date = new RegExp("^((((19|20)(([02468][048])|([13579][26]))-02-29))|((20[0-9][0-9])|(19[0-9][0-9]))-((((0[1-9])|(1[0-2]))-((0[1-9])|(1\d)|(2[0-8])))|((((0[13578])|(1[02]))-31)|(((0[1,3-9])|(1[0-2]))-(29|30)))))$");
var patt_date = new RegExp("^[0-9]{4}-(((0[13578]|(10|12))-(0[1-9]|[1-2][0-9]|3[0-1]))|(02-(0[1-9]|[1-2][0-9]))|((0[469]|11)-(0[1-9]|[1-2][0-9]|30)))$");
if (patt_date.test(document.getElementById("datefrom").value) == false){errFound = errFound + 1;document.getElementById("datefrom").className = "error";}
if (errFound > 0)
alert('Please correct red colored field!');
else
return true;
return false;
}
Above code should work with YYYY-MM-DD format, but fail to validate date such as "2009-02-29"
The commented code should work (//var patt_date = new RegExp...), it can catch "2009-02-29", but it ruin the validation when i put invalid data and try to correct it, it keeps complain there something wrong with form value after i had correct them (especially on form with multiple input)
Maybe someone can fix the current regex?
Edited, what i want just a simple replacement for above regexp, mean a new regexp pattern not the whole new method to validate date
And for reference, i simply grab the regexp pattern from:
http://www.regexlib.com/REDetails.aspx?regexp_id=694 and
http://www.regexlib.com/REDetails.aspx?regexp_id=933
Tested with 2009-02-29, 1st link work & 2nd not. Again the problem was only the 2nd regexp didn't detect value 2009-02-29 as invalid while 1st can (but it ruin my code? so it's must be there something wrong with it).
Thanks,
Dels
Don't do the whole date validation with a regular expression, that's really pushing the limits of what regexps were designed for. I would suggest this procedure instead:
Check date against regexp /^\d{4}-\d{2}-\d{2}$/
Extract year, month, and day using substr() and convert to integers
Use some if statements to validate the integers. Like so:
if (month == 2) {
if (day == 29) {
if (year % 4 != 0 || year % 100 == 0 && year % 400 != 0) {
// fail
}
}
else if (day > 28) {
// fail
}
}
else if (month == 4 || month == 6 || month == 9 || month == 11) {
if (day > 30) {
// fail
}
}
else {
if (day > 31) {
// fail
}
(That could certainly be written more concisely) Alternatively, you could probably perform this validation using Javascript's Date class - you might have to do something like parsing the date, converting it back to a string, and checking if the two strings are equal. (I'm not a Javascript expert)
I kinda agree with David on this... Regex matches should not be used as an exclusive criterion to decide if the passed date is, in fact, valid. The usual procedure in Javascript validation involves a few steps :
a. The first step is to ensure that the passed string matches expected date formats by matching it against a Regex. The following may be a stricter Regex pattern.
// Assuming that the only allowed separator is a forward slash.
// Expected format: yyyy-mm-dd
/^[12][90][\d][\d]-[0-3]?[\d]-[01]?[\d]$/
b. The second step is to parse the string into a Date object which returns the no. of milliseconds since 1970. Use this number as a parameter for the Date constructor.
c. Since JS automatically rolls over the passed date to the nearest valid value, you still cannot be certain if the Date object created matches that which was passed. To determine if this happened, the best way is to split the passed string according to the separator and compare individual date components:
// d is the created Date object as explained above.
var arrDateParts = inputDate.split("-");
if ((d.getFullYear() == arrDateParts[0]) && (d.getMonth() == arrDateParts[1]) && (d.getDate() == arrDateParts[2]))
return true;
else
return false;
This javascript code validates date exactly. You can copy it and test it in your browser.
var regDate = '^(19[0-9]{2}|2[0-9]{3})-(0[1-9]{1}|1[0-2]{1}){1}-(0[1-9]|(1|2)[0-9]|3[0-1]){1}$';
var txt='2010-01-31';
if(txt.match(regDate))
{
alert('date match');
}

endsWith in JavaScript

How can I check if a string ends with a particular character in JavaScript?
Example: I have a string
var str = "mystring#";
I want to know if that string is ending with #. How can I check it?
Is there a endsWith() method in JavaScript?
One solution I have is take the length of the string and get the last character and check it.
Is this the best way or there is any other way?
UPDATE (Nov 24th, 2015):
This answer is originally posted in the year 2010 (SIX years back.) so please take note of these insightful comments:
Shauna -
Update for Googlers - Looks like ECMA6 adds this function. The MDN article also shows a polyfill. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
T.J. Crowder -
Creating substrings isn't expensive on modern browsers; it may well have been in 2010 when this answer was posted. These days, the simple this.substr(-suffix.length) === suffix approach is fastest on Chrome, the same on IE11 as indexOf, and only 4% slower (fergetaboutit territory) on Firefox: https://jsben.ch/OJzlM And faster across the board when the result is false: jsperf.com/endswith-stackoverflow-when-false Of course, with ES6 adding endsWith, the point is moot. :-)
ORIGINAL ANSWER:
I know this is a year old question... but I need this too and I need it to work cross-browser so... combining everyone's answer and comments and simplifying it a bit:
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
Doesn't create a substring
Uses native indexOf function for fastest results
Skip unnecessary comparisons using the second parameter of indexOf to skip ahead
Works in Internet Explorer
NO Regex complications
Also, if you don't like stuffing things in native data structure's prototypes, here's a standalone version:
function endsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
EDIT: As noted by #hamish in the comments, if you want to err on the safe side and check if an implementation has already been provided, you can just adds a typeof check like so:
if (typeof String.prototype.endsWith !== 'function') {
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
}
/#$/.test(str)
will work on all browsers, doesn't require monkey patching String, and doesn't require scanning the entire string as lastIndexOf does when there is no match.
If you want to match a constant string that might contain regular expression special characters, such as '$', then you can use the following:
function makeSuffixRegExp(suffix, caseInsensitive) {
return new RegExp(
String(suffix).replace(/[$%()*+.?\[\\\]{|}]/g, "\\$&") + "$",
caseInsensitive ? "i" : "");
}
and then you can use it like this
makeSuffixRegExp("a[complicated]*suffix*").test(str)
Unfortunately not.
if( "mystring#".substr(-1) === "#" ) {}
Come on, this is the correct endsWith implementation:
String.prototype.endsWith = function (s) {
return this.length >= s.length && this.substr(this.length - s.length) == s;
}
using lastIndexOf just creates unnecessary CPU loops if there is no match.
This version avoids creating a substring, and doesn't use regular expressions (some regex answers here will work; others are broken):
String.prototype.endsWith = function(str)
{
var lastIndex = this.lastIndexOf(str);
return (lastIndex !== -1) && (lastIndex + str.length === this.length);
}
If performance is important to you, it would be worth testing whether lastIndexOf is actually faster than creating a substring or not. (It may well depend on the JS engine you're using...) It may well be faster in the matching case, and when the string is small - but when the string is huge it needs to look back through the whole thing even though we don't really care :(
For checking a single character, finding the length and then using charAt is probably the best way.
Didn't see apporach with slice method. So i'm just leave it here:
function endsWith(str, suffix) {
return str.slice(-suffix.length) === suffix
}
From developer.mozilla.org String.prototype.endsWith()
Summary
The endsWith() method determines whether a string ends with the characters of another string, returning true or false as appropriate.
Syntax
str.endsWith(searchString [, position]);
Parameters
searchString :
The characters to be searched for at the end of this string.
position :
Search within this string as if this string were only this long; defaults to this string's actual length, clamped within the range established by this string's length.
Description
This method lets you determine whether or not a string ends with another string.
Examples
var str = "To be, or not to be, that is the question.";
alert( str.endsWith("question.") ); // true
alert( str.endsWith("to be") ); // false
alert( str.endsWith("to be", 19) ); // true
Specifications
ECMAScript Language Specification 6th Edition (ECMA-262)
Browser compatibility
return this.lastIndexOf(str) + str.length == this.length;
does not work in the case where original string length is one less than search string length and the search string is not found:
lastIndexOf returns -1, then you add search string length and you are left with the original string's length.
A possible fix is
return this.length >= str.length && this.lastIndexOf(str) + str.length == this.length
if( ("mystring#").substr(-1,1) == '#' )
-- Or --
if( ("mystring#").match(/#$/) )
Just another quick alternative that worked like a charm for me, using regex:
// Would be equivalent to:
// "Hello World!".endsWith("World!")
"Hello World!".match("World!$") != null
String.prototype.endsWith = function(str)
{return (this.match(str+"$")==str)}
String.prototype.startsWith = function(str)
{return (this.match("^"+str)==str)}
I hope this helps
var myStr = “ Earth is a beautiful planet ”;
var myStr2 = myStr.trim();
//==“Earth is a beautiful planet”;
if (myStr2.startsWith(“Earth”)) // returns TRUE
if (myStr2.endsWith(“planet”)) // returns TRUE
if (myStr.startsWith(“Earth”))
// returns FALSE due to the leading spaces…
if (myStr.endsWith(“planet”))
// returns FALSE due to trailing spaces…
the traditional way
function strStartsWith(str, prefix) {
return str.indexOf(prefix) === 0;
}
function strEndsWith(str, suffix) {
return str.match(suffix+"$")==suffix;
}
I don't know about you, but:
var s = "mystring#";
s.length >= 1 && s[s.length - 1] == '#'; // will do the thing!
Why regular expressions? Why messing with the prototype? substr? c'mon...
I just learned about this string library:
http://stringjs.com/
Include the js file and then use the S variable like this:
S('hi there').endsWith('hi there')
It can also be used in NodeJS by installing it:
npm install string
Then requiring it as the S variable:
var S = require('string');
The web page also has links to alternate string libraries, if this one doesn't take your fancy.
If you're using lodash:
_.endsWith('abc', 'c'); // true
If not using lodash, you can borrow from its source.
function strEndsWith(str,suffix) {
var reguex= new RegExp(suffix+'$');
if (str.match(reguex)!=null)
return true;
return false;
}
So many things for such a small problem, just use this Regular Expression
var str = "mystring#";
var regex = /^.*#$/
if (regex.test(str)){
//if it has a trailing '#'
}
Its been many years for this question. Let me add an important update for the users who wants to use the most voted chakrit's answer.
'endsWith' functions is already added to JavaScript as part of ECMAScript 6 (experimental technology)
Refer it here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
Hence it is highly recommended to add check for the existence of native implementation as mentioned in the answer.
function check(str)
{
var lastIndex = str.lastIndexOf('/');
return (lastIndex != -1) && (lastIndex == (str.length - 1));
}
A way to future proof and/or prevent overwriting of existing prototype would be test check to see if it has already been added to the String prototype. Here's my take on the non-regex highly rated version.
if (typeof String.endsWith !== 'function') {
String.prototype.endsWith = function (suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
}
#chakrit's accepted answer is a solid way to do it yourself. If, however, you're looking for a packaged solution, I recommend taking a look at underscore.string, as #mlunoe pointed out. Using underscore.string, the code would be:
function endsWithHash(str) {
return _.str.endsWith(str, '#');
}
After all those long tally of answers, i found this piece of code simple and easy to understand!
function end(str, target) {
return str.substr(-target.length) == target;
}
if you dont want to use lasIndexOf or substr then why not just look at the string in its natural state (ie. an array)
String.prototype.endsWith = function(suffix) {
if (this[this.length - 1] == suffix) return true;
return false;
}
or as a standalone function
function strEndsWith(str,suffix) {
if (str[str.length - 1] == suffix) return true;
return false;
}
String.prototype.endWith = function (a) {
var isExp = a.constructor.name === "RegExp",
val = this;
if (isExp === false) {
a = escape(a);
val = escape(val);
} else
a = a.toString().replace(/(^\/)|(\/$)/g, "");
return eval("/" + a + "$/.test(val)");
}
// example
var str = "Hello";
alert(str.endWith("lo"));
alert(str.endWith(/l(o|a)/));
This builds on #charkit's accepted answer allowing either an Array of strings, or string to passed in as an argument.
if (typeof String.prototype.endsWith === 'undefined') {
String.prototype.endsWith = function(suffix) {
if (typeof suffix === 'String') {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
}else if(suffix instanceof Array){
return _.find(suffix, function(value){
console.log(value, (this.indexOf(value, this.length - value.length) !== -1));
return this.indexOf(value, this.length - value.length) !== -1;
}, this);
}
};
}
This requires underscorejs - but can probably be adjusted to remove the underscore dependency.
if(typeof String.prototype.endsWith !== "function") {
/**
* String.prototype.endsWith
* Check if given string locate at the end of current string
* #param {string} substring substring to locate in the current string.
* #param {number=} position end the endsWith check at that position
* #return {boolean}
*
* #edition ECMA-262 6th Edition, 15.5.4.23
*/
String.prototype.endsWith = function(substring, position) {
substring = String(substring);
var subLen = substring.length | 0;
if( !subLen )return true;//Empty string
var strLen = this.length;
if( position === void 0 )position = strLen;
else position = position | 0;
if( position < 1 )return false;
var fromIndex = (strLen < position ? strLen : position) - subLen;
return (fromIndex >= 0 || subLen === -fromIndex)
&& (
position === 0
// if position not at the and of the string, we can optimise search substring
// by checking first symbol of substring exists in search position in current string
|| this.charCodeAt(fromIndex) === substring.charCodeAt(0)//fast false
)
&& this.indexOf(substring, fromIndex) === fromIndex
;
};
}
Benefits:
This version is not just re-using indexOf.
Greatest performance on long strings. Here is a speed test http://jsperf.com/starts-ends-with/4
Fully compatible with ecmascript specification. It passes the tests
Do not use regular expressions. They are slow even in fast languages. Just write a function that checks the end of a string. This library has nice examples: groundjs/util.js.
Be careful adding a function to String.prototype. This code has nice examples of how to do it: groundjs/prototype.js
In general, this is a nice language-level library: groundjs
You can also take a look at lodash
all of them are very useful examples. Adding String.prototype.endsWith = function(str) will help us to simply call the method to check if our string ends with it or not, well regexp will also do it.
I found a better solution than mine. Thanks every one.
For coffeescript
String::endsWith = (suffix) ->
-1 != #indexOf suffix, #length - suffix.length
This is the implementation of endsWith:
String.prototype.endsWith = function (str) {
return (this.length >= str.length) && (this.substr(this.length - str.length) === str);
}
7 years old post, but I was not able to understand top few posts, because they are complex. So, I wrote my own solution:
function strEndsWith(str, endwith)
{
var lastIndex = url.lastIndexOf(endsWith);
var result = false;
if (lastIndex > 0 && (lastIndex + "registerc".length) == url.length)
{
result = true;
}
return result;
}

Categories

Resources