Regexp Numeric with Single Decimal - javascript

I've written the following js with regexp. It works as expected, however I'm looking to simplify it. Could somebody help me out?
.12345 - success
0.12345 - success
12345.12345 - success
0.123456 fail - this I wish was dynamic and not restricted to 5
1.123.45 fail
1.. fail
.. fail
abc - fail
function clearNonNumericChars(field) {
field.val(field.val().replace(/([^0-9\.])/g,""));
field.val(field.val().replace(/^(\d*\.[0-9]{5})\d+$/g,"$1"));
field.val(field.val().replace(/(\.\d*)(\.)$/g,"$1"));
}

Don't deal with numbers as strings.
isNumberValid = function(n) {
return (n == Math.round(n*10000)/10000)
}

You don't need a regex if you don't want one, if you are doing this on keyup. Just filter by keycode/which in your event handler. You've marked the question jQuery, so:
$('input').on('keyup', function (e) {
if ($.inArray(e.which, [48,49,50,51,52,53,54,55,56,57,190]) === -1) {
return true;
}
return false;
});
Note I haven't really tested this, but this basically makes it so the user can't enter anything but numbers or the decimal. Note that they can still paste bad characters in. I'll leave the solution for that to the reader...

Is this what you are looking for? >>
var str = "1a2..b3.C4;56";
str = str.replace(/[^0-9\.]/g,"").replace(/\./,",").replace(/\./g,"").replace(/,/,".");
print(str);
Live test at http://ideone.com/F7wWV

Related

How do I create a function that checks if a date is a palindrome?

My question has two parts. I'm trying to check whether a date is a palindrome or not. In the following code, I continuously get the result of "Not a palindrome" even if the string is in fact a palindrome.
function isPalindrome(str){
var rev = str.reverse;
if(str === rev){
console.log("This is a palindrome.");
}
else{
console.log("Not a palindrome");
}
}
isPalindrome("2002");
The second part to my question is: if I wanted the function to take two arguments function isPalindrome(start_date, end_date)and have it check the dates between for palindrome years and then return those years chronologically, how do I do that? I'm not asking for anyone to actually do it for me. I'm just asking for an explanation on how to accomplish it.
Thanks in advance.
It could be something with the reverse function you are using. You could output the value of rev to see what's going one.
I would suggest you use this: How do you reverse a string in place in JavaScript?
I'm not familiar with any string reverse() function in anybody's native javascript implementation. But here's something I wrote a while back that does the palindrome thing, fwiw:
String.prototype.reverse = function (){
//Another way to reverse a string is to use Array's reverse:
// "this.split('').reverse().join('')";
//but that's boring, and recursion is fun!
if (this.length < 2) { return this.toString() };
return this.slice(-1) + this.slice(0,-1).reverse();
}
String.prototype.is_palindrome = function (){
return this.toString() === this.reverse();
}
This checks whether a string is a palindrome.
As for the second part of your question, I'm not sure how to do that off the top of my head. I would start by seeing what's natively available via javascript's Date object. Check MDN. You would only have to handle the years, so I'd just figure out the year range first and iterate over that, checking for palindromes along the way.
Are you stripping out the non-numeric characters first?
var strippedDate = str.replace(/[^\d]/g, "");
return strippedDate == strippedDate.reverse();

Allowing both lower and uppercase when doing quiz application in JavaScript?

I am currently doing a quiz in JavaScript and would like it so that the user could type using lowercase or uppercase but it does not effect the result. I have had a look about but I'm struggling to see anything that could help. (I know to add a question, and of course the correct answer - which I am currently developing). Thank you.
function Quiz()
{
var answer = prompt("question here?","");
if (answer=="your answer here")
{
alert ("Correct!");
}
else
alert ("Incorrect");
}
You can convert both sides to lower case by using String.prototy.toLowerCase() function. This will insure that both strings are lower case.
function Quiz()
{
var answer = prompt("question here?","");
if (answer.toLowerCase()=="your answer here".toLowerCase())
{
alert ("Correct!");
}
else
alert ("Incorrect");
}
You want to call String.prototype.toLowerCase on answer. This converts everything with lower case letters so you can compare easily:
if (answer.toLowerCase().trim() == "your answer here".toLowerCase()) {
// ...
}
The trim function removes trailing and leading whitespace in case the user accidentally enters some.

Questions about randomizing script

So today I got interested in learning a script that randomizes each letter/number, such as 0000-0000 and each 0 gets randomized by random letter or number. In my previous post I asked about how to do it and got the script, however; the problem I'm having now is completely understanding the code.
jQuery(document).ready(function ($) {
function randomised(len) {
return Math.floor(Math.random() * len);
}
function randomiseString(str){
var charSet = "abcdefghijklmnopqrstuvwxyz0123456789";
var _str = str.replace(/[^-]/g,function(a){
return charSet[randomised(charSet.length)]
});
return _str;
}
$('.combination').text(function(i,t){
return randomiseString(t);
});
});
So this is the code, and here are some of the stuff I'm wondering about:
var _str = str.replace(/[^-]/g,function(a){
return charSet[randomised(charSet.length)]
});
1) So this is the main part that makes the randomization. I'm now having perhaps silly thoughts but I'm wondering how can I force upper-case all the letters I've set above. I know I could just replace those letters with upper-case letters, but I'd like to know how can I do it with code. Also if I understand correctly it makes the charSet an array?
var _str = str.replace(/[^-]/g,function(a)
2) Why does the function have (a) value? Does it make any difference weather I leave it blank or not?
Thanks in advance!
Javascript doesn't require that the parameters passed to a function match the parameters expected by the function at all. This means that you can safely omit the parameters to any function if you don't need them, and in the code above, instead of
function (a) {
// code that doesn't use a
}
you could use
function () {
// ...
}

Exact string match with javascript regex

I'm struggling with what is probably a very simple regex problem. I'm working on a simple prototype and need to know what page I'm on, so I don't reload it if the user clicks a menu widget to navigate to the same view.
I have two URLs the user can switch between:
http://localhost/TestMVC/Larry/LarryTiles
http://localhost/TestMVC/Larry/LarryTilesList
The URLs can also have some trailing querystring items, like this:
http://localhost/TestMVC/Larry/LarryTilesList?filterValue=servers
LarryTiles is giving me the problem. "/\bLarryTiles\b/" worked on Friday (after answers from other questions here) but this doesn't match now. :)
I need to find exactly the strings "LarryTiles" and "LarryTilesList" in these two URLs but can't quite figure out how to do that. The URL changes between my local machine and the various servers where it's hosted, so I can't rely on position.
EDIT: added the example with a trailing querystring, which I'd forgotten. Sorry :(
You can get the last path segment of an URL like this:
function getLastPathSegment(url) {
var match = url.match(/\/([^\/]+)\/?$/);
if (match) {
return(match[1]);
}
return("");
}
// returns "LarryTiles"
getLastPathSegment("http://localhost/TestMVC/Larry/LarryTiles");
// returns "LarryTilesList"
getLastPathSegment("http://localhost/TestMVC/Larry/LarryTilesList");
So, you could do this:
var endPath = getLastPathSegment(window.location.pathname);
if (endPath == "LarryTiles") {
// some code
} else if (endPath == "LarryTilesList") {
// some code
} else {
// some code
}
You can use this code:
str = 'http://localhost/TestMVC/Larry/LarryTiles?filterValue=servers';
if (str.match(/\/([^\/?]+)(?=\/$|\?|$)/)) {
if (match[1] == 'LarryTiles')
alert('LarryTiles found');
else if (match[1] == 'LarryTilesList')
alert('LarryTilesList found');
}
Seems like what you explained works, otherwise try this: http://jsfiddle.net/Wfz9d/
Do you have a case-sensitivity issue?

jquery match() variable interpolation - complex regexes

I've already looked at this, which was helpful to a point.
Here's the problem. I have a list of users propagated into an element via user click; something like this:
<div id="box">
joe-user
page-joe-user
someone-else
page-someone-else
</div>
On click, I want to make sure that the user has not already been clicked into the div. So, I'm doing something like:
if ( ! $('#box').html().match(rcpt) )
{
update_div();
}
else
{
alert(rcpt+' already exists.');
}
However, with existing lack of interpolation that javascript has for regular expressions, is causing my alert to trigger in the use-case where page-joe-user is selected and then the user selects joe-user, which are clearly not exactly the same.
In Perl I would do something like:
if ( $rcpt =~ /^\Qrcpt\E/ )
{
# code
}
All I want to do is change my match() to be:
if ( ! $('#box').html().match(/^rcpt/) )
{
# code
}
if ( ! $('#box').html().match(rcpt) ) seemed a little promising but it, too, fails. Using new RegExp() also does not work using concatenation of complex RE syntax within the function IE $('#box').html().match(new RegExp('^'+rcpt)). I also tried $('#box').html().match('/^'+rcpt'/'). I can only imagine that I'm missing something. I'm pretty new to javascript.
I don't seem to be able to find anything that really addresses such a use-case, here on this site.
TIA
The match function only works on strings, not jQuery objects.
The best way to do this is to put each username into a separate HTML tag.
For example:
<ul id="users">
<li>joe-user</li>
<li>page-joe-user</li>
<li>someone-else</li>
<li>page-someone-else</li>
</ul>
You can then write the following:
if($('#users li').is(function () { return $(this).text() === rcpt; }))
If you want to do it your way, you should call text() to get the string inside the element. ($('#box').text().match(...))
EDIT: The best way to do this using your HTML would be to split the string.
For example:
var userExists = false;
var users = $('#box').text().split(/\r?\n/);
for(var i = 0; i < users.length; i++) { //IE doesn't have indexOf
if (users[i] == rcpt) {
userExists = true;
break;
}
}
if (userExists) {
//Do something
}
This has the added benefit of not being vulnerable to regex-injection.

Categories

Resources