RegExp filter in JavaScript (Angular.js) - javascript

I want to custom filter in Angular.js.
In case an object has name == null, and I insert "u" to filter-> it returns obj, which name == null because re.test(null)=true, but others characters are returning false. Can you tell me why? How can I prevent this case?

You need to check if obj.name is also defined before testing it with regexp:
$scope.searchFilter = function(obj) {
var re = new RegExp($scope.searchText, 'i');
return !$scope.searchText || (obj.name && re.test(obj.name)) || re.test(obj.age.toString());
};
Otherwise, null casted to String type yields "null" and it's matched of course.
Demo: http://jsfiddle.net/26fZb/232/

Related

Way to test empty length property for null and return a string?

I am working through a challenge and trying to set it up so in the event that you pass a string you can determine if there are between 2 and 4 of the letter argument in that string.
My testing of the function worked, however if the matched array is 0 length (in the event there are no matching letters in said string) there is no way to measure the length. I get the error : TypeError: Cannot read property 'length' of null
I tried using a conditional that would return a string if the length was null. Didn't work, I'm not sure if there is a way to funnel this error into a conditional. Any ideas?
TLDR: Is there a way catch to TypeError: Cannot read property 'length' of null before it throws an error?
function countLetters(string, letter) {
let regex = new RegExp(letter, 'g');
let matched = string.match(regex);
if (matched.length == null) {
return "There are no matching characters.";
} else {
let totalLetters = matched.length;
return (totalLetters >= 2 && totalLetters <= 4)? true : false;
}
}
countLetters('Letter', 'e');
true
countLetters('Letter', 'r');
false
countLetters('Letter', 'z');
//TypeError: Cannot read property 'length' of null
If(matched == null || matched.length != 0)
You can try let matched = string.match(regex) || [];
matched.length == null will always be false, so try matched.length === 0
two changes required to make it work as you need:
handle null when no match is found
check for length appropriately
corrected code below:
function countLetters(string, letter) {
let regex = new RegExp(letter, 'g');
let matched = string.match(regex) || [];
if (matched.length == 0) {
return "There are no matching characters.";
} else {
let totalLetters = matched.length;
return (totalLetters >= 2 && totalLetters <= 4)? true : false;
}
}
i would strongly advise that you name your method appropriately. it isn't aligned with the return value or it's type. also, you return either string or a boolean value. one should refrain from that. return values of the same type irrespective of whether a match is found or otherwise.

Easier way to have RegExp.test() return false for null values?

let regex = /[a-z]+/;
regex.test('a'); // true
regex.test(''); // false
regex.test(null); // true
regex.test(undefined); // true
So based on this link, Is it a bug in Ecmascript - /\S/.test(null) returns true?, it looks like the null value is coerced to a string 'null'. WTF? Why on earth is this designed this way? I also can't find any documentation on this behavior. Is there a way to return false for null/undefined values (without hardcoding in checks for 'null', etc.)?
If you're testing a variable, you could do:
regex.test(var || '')
so that it will default to the empty string if it's not set.
The argument of RegExp.test() is expected to be a string. If it isn't, it is converted to a string:
var regex = /\[object Object\]/;
console.log(regex.test({})); // true
This is standard behavior in JavaScript. E. g. "null".replace(null, {}) === "[object Object]".
Follow Check if a variable is a string to check whether or not the argument is a string:
if (typeof myVar === 'string' || myVar instanceof String) { ... }
else return false;
You can override test method.
old = regex.test
regex.test = function(str){
str = str? str: "";
return old.call(this, str);
}
regex.test(null); // false
One way is to get your expected output is to check the value first and replace it with "" empty string in case of null or undefined
let regex = /[a-z]+/;
function test (inp){
return regex.test(inp? inp: '');
}
test(null); // false
test(undefined); // false

Not Understanding How to Capitalizing Text in Angular

My friend helped me write a custom filter in AngularJS to help me capitalize one of the values in my object for one of my arrays. But didn't have time to explain to me what he did. Was just wondering if anyone can be kind to help me understand this block of code:
.filter('capitalizetext', function() {
return function(name) {
name = ( name === undefined || name === null ) ? '' : name;
return name.toString().toLowerCase().replace( /\b([a-z])/g, function(change) {
return change.toUpperCase();
});
};
})
1st part that I don't understand is:
name = ( name === undefined || name === null ) ? '' : name;
Why did he do this?
2nd part I don't understand is:
return name.toString().toLowerCase().replace( /\b([a-z])/g,
I understand that he is changing the string to all lowercase so that he can eventually convert it to capitalize the string but what is this: ( /\b([a-z])/g
Not really following what he did there.
Please help!
name = ( name === undefined || name === null ) ? '' : name;
This ensures that name is never null or undefined when using it later.
return name.toString().toLowerCase().replace( /\b([a-z])/g, function(change) {
return change.toUpperCase();
});
};
First change everything to lowercase and replace the first character of EVERY word to the uppercase version. \b is a boundary matcher:
E.g. suppose name = "capItalIze me"
Then
name.toString().toLowerCase(); // => name = "capitalize me"
/\b([a-z])/g // means find first letter of every word so will match "c" and "m"
replace( /\b([a-z])/g, function(change) {return change.toUpperCase();});} // change 'c' to 'C' and 'm' to 'M';
In the first part:
name = ( name === undefined || name === null ) ? '' : name;
He checks to see if the string is truthy in his "definition", checking if it is undefined or null (as a null/undefined string could raise errors), else if it is, he sets it to an empty string to avoid errors.
The second part he uses a regex expression to modify the string to the filter specification. You can read about regex expression here. I am not well versed in regex, but I think you are on the right track when he converts all characters to lowercase, check the comment made above for the regex explanation, however, if this is the case, he could just do this...
string = string.toLowerCase()
string = string.substr(0, 1).toUpperCase() + string.substr(1);

Javascript null or empty string does not work

I am trying to test that my string is null or empty, however it does not work.
My Code :
var veri = {
YeniMusteriEkleTextBox: $('#MyTextbox').val(),
};
if (veri.YeniMusteriEkleTextBox === "" ||
veri.YeniMusteriEkleTextBox == '' ||
veri.YeniMusteriEkleTextBox.length == 0 ||
veri.YeniMusteriEkleTextBox == null) {
alert("Customer Name can not be empty!!!");
}
How can ı check YeniMusteriEkleTextBox is null or empty ?
I would use the ! operator to test if it is empty, undefined etc.
if (!veri.YeniMusteriEkleTextBox) {
alert("Customer Name can not be empty!!!");
}
Also you do not need the comma after YeniMusteriEkleTextBox: $('#MyTextbox').val(),
Also testing for a length on an object that may be undefined will throw an error as the length will not be 0, it will instead be undefined.
You need to .trim the value to remove leading and trailing white space:
var veri = {
YeniMusteriEkleTextBox: $('#YeniMusteriAdiTextbox_I').val().trim()
};
The .trim method doesn't exist on some older browsers, there's a shim to add it at the above MDN link.
You can then just test !veri.YeniMusteriEkleTextBox or alternatively veri.YeniMusteriEkleTextBox.length === 0:
if (!veri.YeniMusteriEkleTextBox) {
alert("Customer Name can not be empty!!!");
}
You should use
if (!veri.YeniMusteriEkleTextBox) {
This also checks for undefined which is not the same as null
Since no one else is suggestion $.trim, I will
Note I removed the trailing comma too and use the ! not operator which will work for undefined, empty null and also 0, which is not a valid customer name anyway
var veri = {
YeniMusteriEkleTextBox: $.trim($('#MyTextbox').val())
};
if (!veri.YeniMusteriEkleTextBox) {
alert("Customer Name can not be empty!!!");
}

C# String.IsNullOrEmpty Javascript equivalent

I want to try to do string call equivalent to the C# String.IsNullOrEmpty(string) in javascript. I looked online assuming that there was a simple call to make, but I could not find one.
For now I am using a if(string === "" || string === null) statement to cover it, but I would rather use a predefined method (I keep getting some instances that slip by for some reason)
What is the closest javascript (or jquery if then have one) call that would be equal?
You're overthinking. Null and empty string are both falsey values in JavaScript.
if(!theString) {
alert("the string is null or empty");
}
Falsey:
false
null
undefined
The empty string ''
The number 0
The number NaN
If, for whatever reason, you wanted to test only null and empty, you could do:
function isNullOrEmpty( s )
{
return ( s == null || s === "" );
}
Note: This will also catch undefined as #Raynos mentioned in the comments.
if (!string) {
// is emtpy
}
What is the best way to test for an empty string with jquery-out-of-the-box?
If you know that string is not numeric, this will work:
if (!string) {
.
.
.
You can create one Utility method which can be reused in many places such as:
function isNullOrEmpty(str){
var returnValue = false;
if ( !str
|| str == null
|| str === 'null'
|| str === ''
|| str === '{}'
|| str === 'undefined'
|| str.length === 0 ) {
returnValue = true;
}
return returnValue;
}
you can just do
if(!string)
{
//...
}
This will check string for undefined, null, and empty string.
To be clear, if(!theString){//...} where theString is an undeclared variable will throw an undefined error, not find it true. On the other hand if you have: if(!window.theString){//...} or var theString; if(!theString){//...} it will work as expected. In the case where a variable may not be declared (as opposed to being a property or simply not set), you need to use: if(typeof theString === 'undefined'){//...}
My preference is to create a prototype function that wraps it up for you.
Since the answer that is marked as correct contains a small error, here is my best try at coming up with a solution. I have two options, one that takes a string, the other takes a string or a number, since I assume many people are mixing strings and numbers in javascript.
Steps:
-If the object is null it is a null or empty string.
-If the type is not string (or number) it's string value is null or empty. NOTE: we might throw an exception here as well, depending on preferences.
-If the trimmed string value has a length that is small than 1 it is null or empty.
var stringIsNullOrEmpty = function(theString)
{
return theString == null || typeof theString != "string" || theString.trim().length < 1;
}
var stringableIsNullOrEmpty = function(theString)
{
if(theString == null) return true;
var type = typeof theString;
if(type != "string" && type != "number") return true;
return theString.toString().trim().length < 1;
}
you can say it by logic
Let say you have a variable name a strVal, to check if is null or empty
if (typeof (strVal) == 'string' && strVal.length > 0)
{
// is has a value and it is not null :)
}
else
{
//it is null or empty :(
}

Categories

Resources