How do I make an case-insensitive search? - javascript

$("#input").keyup(function () {
var userInput = $(this).val();
$("#list div").map(function (index, value) {
$(value).toggle($(value).text().toString().indexOf(userInput) >= 0);
});
});
here is the code
How do I make it case insensitive? is it possible? I tried using css to force lowercase on user input but did not help.

This should do the trick
var userInputLower = userInput.toLowerCase();
var shouldToggle = $(value).text().toLowerCase().indexOf(userInputLower) >= 0;
$(value).toggle(shouldToggle);

Use string.toLowerCase()
"HELLOOOooo".toLowerCase(); // hellooooo

The idea behind case insensitive searches it to convert both the source (string to look for) as well as the target (strings that are compared to the source) to lowercase.
Then both have the same casing, which makes it case insensitive.
Converting both the source and target strings to uppercase will give the same result, but to lowercase is used most often.

Related

Three Char Month and Culture matching in javascript

I have a multi cultural website, where I allow users to enter values in a dd-MMM-yyyy format. I am able to determine the different values based upon their culture in C# (May, English = May, German = Mai)
the problem I am having is the javascript validation of these months. I am able to build the list of acceptable values:
english:
^Jan$|^Feb$|^Mar$|^Apr$|^May$|^Jun$|^Jul$|^Aug$|^Sep$|^Oct$|^Nov$|^Dec$
German:
^Jan$|^Feb$|^Mrz$|^Apr$|^Mai$|^Jun$|^Jul$|^Aug$|^Sep$|^Okt$|^Nov$|^Dez$
I just want to make this regular expression case insensitive. but all the references I see are all pointing me to the /gi flag, but I all of the examples make no sense. I have tried the following and it just doesn't work:
var shouldMatch = "may";
var regexPattern = "^Jan$|^Feb$|^Mar$|^Apr$|^May$|^Jun$|^Jul$|^Aug$|^Sep$|^Oct$|^Nov$|^Dec$/gi"
if(shouldMatch.match(regexPattern) != null) {
//this should happen
}
What am I doing wrong? the regex help out there for javascript is killing me.
jsFiddle Demo
But what about trying to match "mAR" or "MAr", etc.? This quickly becomes an interesting scenario. In my opinion, an easy way to do this is to just match to upper case
var shouldMatch = "May";
var regexPattern = "^JAN$|^FEB$|^MAR$|^APR$|^MAY$|^JUN$|^JUL$|^AUG$|^SEP$|^OCT$|^NOV$|^DEC$";
if(shouldMatch.toUpperCase().match(regexPattern) != null) {
alert("match");
}
regexPattern is a string, not a regular expression.
Convert it to a RegExp before you use it with match:
var regexPattern = new RegExp("^JAN$|^FEB$|^MAR$|^APR$|^MAY$|^JUN$|^JUL$|^AUG$|^SEP$|^OCT$|^NOV$|^DEC$", "gi");
And also, convert the shouldMatch to upper case before you use it:
shouldMatch = shouldMatch.toUpperCase();
Your regular expression should not be a string:
var shouldMatch = "may";
var regexPattern = /^Jan$|^Feb$|^Mar$|^Apr$|^May$|^Jun$|^Jul$|^Aug$|^Sep$|^Oct$|^Nov$|^Dec$/i;
if(shouldMatch.match(regexPattern) != null) {
// this seems happened
}
This should work for you.
Changed to using test
No need for the global "g" flag as you are testing the whole string from beginning "^" to end "$"
Changed string regexPattern into a RegExp object
The "i" flag is needed because you want case insensitive.
Javascript
var shouldMatch = "may";
var regexPattern = /^Jan$|^Feb$|^Mar$|^Apr$|^May$|^Jun$|^Jul$|^Aug$|^Sep$|^Oct$|^Nov$|^Dec$/i;
if(regexPattern.test(shouldMatch)) {
alert(shouldMatch);
}
On jsfiddle
You could also make it a little shorter and a little less ugly by doing this
var regexPattern = /^(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)$/i;
On jsfiddle
As an alternative to regex, you could also use String.indexOf and Array.some, and try each pattern to see if it is in the string you are testing. This example will require a modern browser or a "shim"/"polyfill" for older browsers. You could also check equality "===" if you want to match the whole string rather than see if it is contained in.
Javascript
var shouldMatch = "may";
var patterns = "Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec".split("|");
var matched = patterns.some(function (pattern) {
if (shouldMatch.toLowerCase().indexOf(pattern.toLowerCase()) !== -1) {
alert(shouldMatch);
return true;
}
return false;
});
On jsfiddle
Or run the possibilities together-
var Rx=/^(jan|feb|m(ar|rz)|apr|ma[iy]|jun|jul|aug|sep|o[ck]t|nov|de[cz])$/i
Rx.test('may');

Javascript issue: regex issue finding matches

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)$/
}

Japanese characters :Convert lowerCase to upperCase using jquery

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;
}

Find word with regex in Javascript

How can I find a word with regular expression in Javascript?
For example:
http://127.0.0.1/w/?id=2&tab=wow
I want to know if this link contains the word 'tab'.
var string = 'http://127.0.0.1/w/?id=2&tab=wow'
var containsTab = string.indexOf('tab') > -1
Or if you really want to use a regex:
var containsTab = string.match(/tab/);
jQuery is not a language. It's a library written for JavaScript.
You don't need a regular expression.
Use indexOf.
var str = 'http://127.0.0.1/w/?id=2&tab=wow';
if(str.indexOf('tab') > -1) {
// Contains string
} else {
// Doesn't
}

How to know if JavaScript string.replace() did anything?

The replace function returns the new string with the replaces, but if there weren't any words to replace, then the original string is returned. Is there a way to know whether it actually replaced anything apart from comparing the result with the original string?
A simple option is to check for matches before you replace:
var regex = /i/g;
var newStr = str;
var replaced = str.search(regex) >= 0;
if(replaced){
newStr = newStr.replace(regex, '!');
}
If you don't want that either, you can abuse the replace callback to achieve that in a single pass:
var replaced = false;
var newStr = str.replace(/i/g, function(token){replaced = true; return '!';});
As a workaround you can implement your own callback function that will set a flag and do the replacement. The replacement argument of replace can accept functions.
Comparing the before and after strings is the easiest way to check if it did anything, there's no intrinsic support in String.replace().
[contrived example of how '==' might fail deleted because it was wrong]
Javascript replace is defected by design. Why? It has no compatibility with string replacement in callback.
For example:
"ab".replace(/(a)(b)/, "$1$2")
> "ab"
We want to verify that replace is done in single pass. I was imagine something like:
"ab".replace(/(a)(b)/, "$1$2", function replacing() { console.log('ok'); })
> "ab"
Real variant:
"ab".replace(/(a)(b)/, function replacing() {
console.log('ok');
return "$1$2";
})
> ok
> "$1$2"
But function replacing is designed to receive $0, $1, $2, offset, string and we have to fight with replacement "$1$2". The solution is:
"ab".replace(/(a)(b)/, function replacing() {
console.log('ok');
// arguments are $0, $1, ..., offset, string
return Array.from(arguments).slice(1, -2)
.reduce(function (pattern, match, index) {
// '$1' from strings like '$11 $12' shouldn't be replaced.
return pattern.replace(
new RegExp("\\$" + (index + 1) + "(?=[^\\d]|$)", "g"),
match
);
}, "$1$2");
});
> ok
> "ab"
This solution is not perfect. String replacement itself has its own WATs. For example:
"a".replace(/(a)/, "$01")
> "a"
"a".replace(/(a)/, "$001")
> "$001"
If you want to care about compatibility you have to read spec and implement all its craziness.
If your replace has a different length from the searched text, you can check the length of the string before and after. I know, this is a partial response, valid only on a subset of the problem.
OR
You can do a search. If the search is successfull you do a replace on the substring starting with the found index and then recompose the string. This could be slower because you are generating 3 strings instead of 2.
var test = "Hellllo";
var index = test.search(/ll/);
if (index >= 0) {
test = test.substr(0, index - 1) + test.substr(index).replace(/ll/g, "tt");
}
alert(test);
While this will require multiple operations, using .test() may suffice:
const regex = /foo/;
const yourString = 'foo bar';
if (regex.test(yourString)) {
console.log('yourString contains regex');
// Go ahead and do whatever else you'd like.
}
The test() method executes a search for a match between a regular expression and a specified string. Returns true or false.
With indexOf you can check wether a string contains another string.
Seems like you might want to use that.
have a look at string.match() or string.search()
After doing any RegExp method, read RegExp.lastMatch property:
/^$/.test(''); //Clear RegExp.lastMatch first, Its value will be ''
'abcd'.replace(/bc/,'12');
if(RegExp.lastMatch !== '')
console.log('has been replaced');
else
console.log('not replaced');

Categories