I'm sure it's simple and I just don't see it. I've been searching for examples and as short and simple as they are, I can't seem to find my issue.
I wish to validate a Postal Code field and use the Canadian Postal code format. I found an expression I wish to use and it looks like the following:
var validZIP={
"US":"^\d{5}([\-]?\d{4})?$",
"UK":"^(GIR|[A-Z]\d[A-Z\d]??|[A-Z]{2}\d[A-Z\d]??)[ ]??(\d[A-Z]{2})$",
"CA":"^([ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ])\ {0,1}(\d[ABCEGHJKLMNPRSTVWXYZ]\d)$"
}
Please note the CA which stands for CAnada in this case.
My onChange function calls the following method (onchange class checkValidPostal(this) from the input):
function checkValidPostal(input)
{
var re = new RegExp(validZIP["CA"]);
var value = input.value.toUpperCase();
if (value.match(re))
{
input.value = value;
return true;
}
input.value = "";
return false;
}
I have checked the RegEx line using:
http://www.regular-expressions.info/javascriptexample.html and it works great on that page, but for some reason I can't get it to work on mine!
Please help.
There's a problem : as you use strings instead of regex literals, you lack some escapements.
Besides, you probably want to use test instead of match.
You could fix that like this :
var validZIP={
"US": /^\d{5}([\-]?\d{4})?$/,
"UK": /^(GIR|[A-Z]\d[A-Z\d]??|[A-Z]{2}\d[A-Z\d]??)[ ]??(\d[A-Z]{2})$/,
"CA": /^([ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ])\ {0,1}(\d[ABCEGHJKLMNPRSTVWXYZ]\d)$/
}
function checkValidPostal(input) {
var re = validZIP["CA"];
var value = input.value.toUpperCase();
if (re.test(value)) {
input.value = value;
return true;
}
input.value = "";
return false;
}
Inside a string you'll need to double-escape your backslashes, else they are already escaped by the string and there are no backslashes remaining by the time the RegEx constructor gets the string.
Try putting pattern instead of strings in validZIP:
var validZIP={
"US":/^\d{5}([\-]?\d{4})?$/,
"UK":/^(GIR|[A-Z]\d[A-Z\d]??|[A-Z]{2}\d[A-Z\d]??)[ ]??(\d[A-Z]{2})$/,
"CA":/^([ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ])\ {0,1}(\d[ABCEGHJKLMNPRSTVWXYZ]\d)$/
}
Related
I have function that is supposed to "clean" a string and i'd like to use replace() to do that, but I can't figure out why the following code is not working when the text comes from an input[text].
for instance :
console.log(getCleanText("ééé")); // works fine, it displays : eee
but
// my_id is an input with type="text"
var my_text = document.getElementById("my_id").value
console.log(getCleanText(my_text)); // doesn't work at all, it displays : ééé
the function code is :
function getCleanText(some_text) {
var clean_text = some_text.toLowerCase();
clean_text = clean_text.replace("é", "e");
clean_text = clean_text.split("é").join("e"); // give it another try
return clean_text;
}
any idea ?
I'm willing to bet your problem lies in a misunderstanding of Unicode.
é
é
Those two characters above are two different characters. The first is the letter e, with an accent character (U+0301). The other is a single character, U+00E9.
You need to ensure you're replacing both versions.
I think the character "é" from element value is the different from the "é" constant. To resolve that you can take look at the int value of the input.
var inputEValue = document.getElementById("my_id").charCodeAt(0);
var constantEValue = "é".charCodeAt(0);
Then you will be able to detect what characters you are replacing.
If you want to just remove accents from text, take look at the question Remove accents/diacritics in a string in JavaScript
Try this:
function getCleanText(old_string)
{
var new_string = old_string.toLowerCase();
return new_string.replace(/é/g, 'e');
}
Ed: beaten by the Robert. For reference, see here: What are useful JavaScript methods that extends built-in objects?
Try this:
function cleanText(text) {
var re = new RegExp(/\u0301|\u00e9/g);
return text.replace(re, "e").toLowerCase();
}
cleanText("éééé")
--
Updated to use the proposed UniCode chars by Matt Grande
What is the output of
var my_text = document.getElementById("my_id").value; ?
Depending on your html, you might need to use other functions to get the data. e.g
var my_text = document.getElementById("my_id").innerHTML;
http://jsbin.com/obAmiPe/5/edit?html,js,console,output
I use this function below to quickly find an item in a table
My problem is that this function only searches for text that contains the search string in the given table
I have been trying my best to modify it to match only the text that begins with the search string but not working.
function searchTable(inputVal)
{
var table = $('#supplier_table_body');
table.find('tr').each(function(index, row)
{
var allCells = $(row).find('td');
if(allCells.length > 0)
{
var found = false;
allCells.each(function(index, td)
{
var regExp = new RegExp(inputVal, '^i');
if(regExp.test($(td).text()))
{
found = true;
return false;
}
});
if(found == true)$(row).show();else $(row).hide();
}
});
}
Here is my jquery
$('#itemname').keyup(function()
{
searchTable($(this).val());
});
The string start anchor is not a regex modifier flag, but needs to be part of the expression:
var regExp = new RegExp('^'+inputVal, 'i');
I think you should use \b: new RegExp("\\b" + inputVal, "i"). It finds a match that begins with inputVal.
Not sure if it works, but you may try to add a caret ( ^ ) before the inputVal, while creating the RegExp.
This should only allow words starting with inputVal.
Cheers,
EDIT:
Like so :
new RegExp("^" + inputVal, "i")
This answer posted as a community wiki answer because I think it solves the problem you're having and simplifies your code (but is too long to post as a comment), so I'd suggest, though currently untested, amending your function to:
function searchTable(needle){
var table = $('#supplier_table_body'),
cells = table.find('td');
cells.filter(function(){
return this.textContent.indexOf(needle) !== 0;
}).closest('tr').hide();
}
Simple proof of concept.
I tried using toUppercase() method to convert japanese characters to uppercase but it return same string with out conversion.
Is there any other way to do this using jquery or javascript.
fieldValue = "ショウコ"; //japanese string.
function convertToUppercase(fieldValue)
{
convertedValue = fieldValue.toUpperCase();
return convertedValue;
}
Any help would be greatly appreciated!
There's a list of all the "small" letters (known as "youon") on Wikipedia:
ぁぃぅぇぉっゃゅょゎァィゥェォヵㇰヶㇱㇲッㇳㇴㇵㇶㇷㇷ゚ㇸㇹㇺャュョㇻㇼㇽㇾㇿヮ
You could use a switch statement to convert them to their "big" equivalents, which I'll type out here for your convenience:
あいうえおつやゆよわアイウエオカクケシスツトヌハヒフプヘホムヤユヨラリルレロワ
Note that the consonants aren't necessarily read the same way when they're made "big"; for example, 何ヶ月 is read "なんかげつ(nankagetsu)", not "なんけげつ(nankegetsu)". っ, which indicates a glottal stop on the next syllable, is read as "tsu" when it's made big.
The "big" vowels indicate that they need to be given their own syllable length. (There's a term for this too, but I'm not a linguist -- sorry!)
I'm a bit ignorant on the names of Japanese characters but I do know that Sugar.js has many methods for manipulating and transforming such characters. It has methods such as zenkaku, hankaku, hiragana, and katakana.
Here's a link to the Sugarjs' String API
Thanks for the help and guided me to right way
Finally I came up with this solution.
function convertBigKana(kanaVal){
var smallKana = Array('ァ','ィ','ゥ','ェ','ォ','ヵ','ヶ','ㇱ','ㇲ','ッ','ㇳ','ㇴ','ㇵ','ㇶ','ㇷ','ㇸ','ㇹ','ㇺ','ャ','ュ','ョ','ㇻ','ㇼ','ㇽ','ㇾ','ㇿ','ヮ');
var bigKana = Array('ア','イ','ウ','エ','オ','カ','ケ','シ','ス','ツ','ト','ヌ','ハ','ヒ','フ','ヘ','ホ','ム','ヤ','ユ','ヨ','ラ','リ','ル','レ','ロ','ワ');
var ckanaVal = '';
for (var i = 0; i < kanaVal.length; i++){
//var index = smallKana.indexOf(kanaVal.charAt(i)); //indexOf and stri[i] don't work on ie
var index = jQuery.inArray(kanaVal.charAt(i), smallKana);
if (index !== -1) {
ckanaVal+= bigKana[index];
}
else
{
ckanaVal+= kanaVal.charAt(i);
}
}
return ckanaVal;
}
Why doesn't the following jQuery code work?
$(function() {
var regex = /\?fb=[0-9]+/g;
var input = window.location.href;
var scrape = input.match(regex); // returns ?fb=4
var numeral = /\?fb=/g;
scrape.replace(numeral,'');
alert(scrape); // Should alert the number?
});
Basically I have a link like this:
http://foo.com/?fb=4
How do I first locate the ?fb=4 and then retrieve the number only?
Consider using the following code instead:
$(function() {
var matches = window.location.href.match(/\?fb=([0-9]+)/i);
if (matches) {
var number = matches[1];
alert(number); // will alert 4!
}
});
Test an example of it here: http://jsfiddle.net/GLAXS/
The regular expression is only slightly modified from what you provided. The global flag was removed, as you're not going to have multiple fb='s to match (otherwise your URL will be invalid!). The case insensitive flag flag was added to match FB= as well as fb=.
The number is wrapped in curly brackets to denote a capturing group which is the magic which allows us to use match.
If match matches the regular expression we specify, it'll return the matched string in the first array element. The remaining elements contain the value of each capturing group we define.
In our running example, the string "?fb=4" is matched and so is the first value of the returned array. The only capturing group we have defined is the number matcher; which is why 4 is contained in the second element.
If you all you need is to grab the value of fb, just use capturing parenthesis:
var regex = /\?fb=([0-9]+)/g;
var input = window.location.href;
var tokens = regex.exec(input);
if (tokens) { // there's a match
alert(tokens[1]); // grab first captured token
}
So, you want to feed a querystring and then get its value based on parameters?
I had had half a mind to offer Get query string values in JavaScript.
But then I saw a small kid abusing a much respectful Stack Overflow answer.
// Revised, cooler.
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)')
.exec(window.location.search);
return match ?
decodeURIComponent(match[1].replace(/\+/g, ' '))
: null;
}
And while you are at it, just call the function like this.
getParameterByName("fb")
How about using the following function to read the query string parameter in JavaScript:
function getQuerystring(key, default_) {
if (default_==null)
default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}
and then:
alert(getQuerystring('fb'));
If you are new to Regex, why not try Program that illustrates the ins and outs of Regular Expressions
i try to allow only number 01 (1) to 53) after / and after 2000 and over....
so i create a regex but it don't seem to work
on this web page: http://www.regular-expressions.info/javascriptexample.html
i tried it and it work well... but when i test in on a web page
10/2010 , 23/2000
function isValidDate(value, format){
var isValid = true;
try{
var inputVal = $(this).val();
var dateWWYYYYRegex = '^(0[1-9]|[1234][0-9]|5[0-3])[-/.](20)\d\d$';
var reg=new RegExp(dateWWYYYYRegex);
if(!reg.test(value)){
isValid = false;
alert("Invalid");
}
}
catch(error){
isValid = false;
}
return isValid;
}
You have to escape backslashes if you're going to make a regex from a string. I'd just use regex syntax, since it's a constant anyway:
var reg = /^(0[1-9]|[1234][0-9]|5[0-3])[-/.](20)\d\d$/;
The regular expression doesn't really make any sense, however. It's not clear what it should be, because your description is also confusing.
edit — OK now that I see what you're doing, that regex should work, I guess.
Why use regex for this task? I think it's the wrong tool for this task
Simply split the string by the slash delimiter, and then use numerical functions to check if the values are in the range you want.
function isValidWeekOfYear(value){
var bits = value.split('/');
if(parseInt(bits[1]) < 2000) { return false; } /* probably also want to do a maximum value here? */
if(parseInt(bits[0]) < 1 || parseInt(bits[0]) > 53) { return false; }
return true;
}
It might need a bit more validation than that, but that should be a good starting point for you. Much less processing overhead than a regex just to parse a couple of numbers (and easier to read too).