I'm using jquery.grep to clean a string and return only digits.
This is what I have:
var TheInputArray = TheInput.slice();
var TheCleanInput = jQuery.grep(TheInputArray, function (a) {
return parseInt(a, 10);
});
I take a string, split it into an array and use the parseInt function to check if it's a number. The problem is that when the value of a is 0, it skips that element. What changes do I need to do to make this code work?
Thanks.
Unfortunately, 0 in Javascript is falsy. So you need to be sure your return value is true, even for a 0.
var TheInputArray = TheInput.slice();
var TheCleanInput = jQuery.grep(TheInputArray, function (a) {
return ! isNaN(parseInt(a, 10));
});
parseInt returns NaN (not a number), if it fails to parse the input. And isNan() will return true if the argument is NaN. So this should help you detect that case.
You can use regular expressions:
var TheCleanInput = TheInput.replace(/\D/g, '');
If you just want to test whether the element in the array is a number, rather than converting it and then building a new array using the converted numbers, you can use the new $.isNumeric function (new in 1.7), which tests whether the argument represents a numeric value:
var TheCleanInput = jQuery.grep(TheInputArray, function (a) { return $.isNumeric(a); });
Note that this does not modify the existing array. If the array contains '5', that will remain a string and not be converted to a number. Use $.map if that's what you want.
The parseInt() function doesn't return a boolean value, it either returns NaN for non-numeric values or the converted value for numeric values. If you try to use the result as a boolean you'll find that NaN and 0 will both be falsy, while any non-zero number will be equivalent to true.
You can use isNan() to check this: return !isNan(parseInt(a,10));
Or you can use jQuery's $.isNumeric(a) function instead (if using jQuery 1.7+).
Or if you just want to remove all non-numeric characters from a string why not use a regex replace:
TheInput.replace(/\D/g,"")
Even if you specifically want the result as an array I think you're best off using the regex and then converting to an array afterwards because it keeps the code simple.
If you're using the current Version of jQuery (1.7), you can use jQuery.isNumeric(a) for that purpose:
var TheCleanInput = jQuery.grep(TheInputArray, function (a) { return $.isNumeric(a); });
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
var filterInt = function(value) {
if (/^(\-|\+)?([0-9]+|Infinity)$/.test(value))
return Number(value);
return NaN;
}
Related
I was trying to compare a regex pattern into my number input and see if it matches:
var number = '490351111313131';
var switchPrefix = new RegExp(/(4903|4905|4911|4936|564182|633110|6333|6759)/);
var stringToArray = number.split('').map(Number);
var x = parseInt(stringToArray.slice(0, 6).join(''), 10); => outputs 490351
console.log(typeof(x), x); => outputs number
if(x.match(switchPrefix)){
console.log(true);
}
However for some reason it always return:
'Match is not a function'
Any idea how to fix this? or why is it working like that?
Thanks!
However for some reason it always return: 'Match is not a function'
Number type variable doesn't have match method.
match is a method of String class, so change your code to
if(String(x).match(switchPrefix)){
console.log(true);
}
You could use RegExp#test,
The test() method executes a search for a match between a regular expression and a specified string. Returns true or false.
because it returns a boolean value, which is wanted here.
function test(s) {
return /^(4903|4905|4911|4936|564182|633110|6333|6759)\d*$/.test(s);
}
console.log(test('490351111313131'));
console.log(test('1490351111313131'));
I have a string, say
var Str = 'My name is 123 and my name is 234'.
Now I split this as
var arrStr = Str.split(' ');
I iterate through the array and have different logic depending upon whether the word is a string or number. How do i check that? I tried typeof which didn't work for me.
EDIT:
After Seeing multiple answers. Now, I am in despair, which is the most efficient way?
If you care only about the numbers, then instead of using split you can use a regular expression like this:
var input = "My name is 123 and my name is 234";
var results = input.match(/\d+/g)
If you care about all pieces, then you can use another expression to find all non-space characters like this:
var input = "My name is 123 and my name is 234";
var results = input.match(/\S+/g)
Then iterate them one by one, and check if a given string is a number or not using the famous isNumeric() function posted by #CMS in this famous question.
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
NOTE: Thanks to #Pointy and if you want them as numbers, input.match(/\d+/g).map(Number).
You need to attempt to convert your array values to an integer.
To iterate them you can use a for loop:
for(i=0;i<arrStr.length;i++) {
var result = !isNaN(+arrStr[i]) ? 'number' : 'string';
console.log(result);
}
Here I'm using a unary + to attempt to convert the value of each array value to a number. If this fails, the result will be NaN. I'm then using JavaScript's isNaN() method to test if this value is NaN. If it isn't, then it's a number, otherwise it's a string.
The result of this using the string you've provided is:
string
string
string
number
string
string
string
string
number
To use this in an if statement, we can simply:
for(i=0;i<arrStr.length;i++) {
if(isNaN(+arrStr[i])) {
/* Process as a string... */
}
else {
/* Process as a number... */
}
}
JSFiddle demo.
To expound on Sniffer's answer...
var input = "My name is 123 and my name is 234";
var numberArray = input.match(/\d+/g);
var wordArray = input.match(/[A-Za-z]+/g);
for (var number in numberArray)
{
//do something
}
for (var word in wordArray)
{
//do something
}
While researching, I found out about the Number() object. This is generally used to work with manipulation of numbers. MDN has a good documentation .
I found out that Number() returns NaN (Not a Number) when not passed a number. Since no number returns NaN, It could be a good way to check whether the passed object is string or a number literal.
So my code would be:
if (Number(arrStr[i]) == NaN){
//string
} else {
//number
}
I have the following function where I'm using regex matching to check for proper date format when a change event happens on the value in the input field.
My problem is that month, day, and year are returning as NaN and I'm not sure why. I'm parsing regex objects [1], [2], and [3] respectively with parseInt() so I'm not sure why they are returning as NaN.
validateDate: function(event) {
var input = $(event.target);
var enteredDate = input.val();
input.destroyValidationMessage();
var pattern = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
var result = pattern.test(enteredDate);
if (result !== null) {
var month = parseInt(result[1], 10);
var day = parseInt(result[2], 10);
var year = parseInt(result[3], 10);
}
}
.test() [MDN] returns a boolean, i.e. true or false and only tells you whether the expression matches the input or not.
Then, since if(result !== null) is always true for result being either true or false, the if statement block is executed.
match[x] is the same as true[x] (or false[x]) and instead of throwing an error, it returns undefined. This is because JavaScript converts the primitive value to an object internally and accessing a non-existing property results in the return value undefined.
Furthermore, parseInt(undefined, 10) returns NaN.
You want to use .match() [MDN]:
var result = enteredDate.match(pattern);
A shorter way of converting a numerical string to a number is using the unary + operator:
var month = +result[1];
which gives you the same result here since the input string only contains digits.
You need to use exec instead of test:
var result = pattern.exec(enteredDate);
More about exec you can read at MDN
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');
In most languages like C# for example given a string you can test (boolean) if that string contains another string, basically a subset of that string.
string x = test2;
if(x.contains("test"))
// do something
How can I do this in a simple way with Javascript/Jquery?
This is done with indexOf, however it returns -1 instead of False if not found.
Syntax
string.indexOf(searchValue[, fromIndex])
Parameters
searchValue -
A string representing the value to search for.
fromIndex -
The location within string to start the search from. It can be any integer between 0 and the length of string. The default value is 0.
Return
The first index in string at which the start of the substring can be found, or -1 if string does not contain any instances of the substring.
As Paolo and cletus said, you can do it using indexOf().
Valid to mention is that it is a javascript function, not a jQuery one.
If you want a jQuery function to do this you can use it:
jQuery.fn.contains = function(txt) { return jQuery(this).indexOf(txt) >= 0; }
The indexOf operator works for simple strings. If you need something more complicated, it's worth pointing out that Javascript supports regular expressions.
A simple contains can also be useful for example:
<div class="test">Handyman</div>
$(".test:contains('Handyman')").html("A Bussy man");
A working example, using just indexOf and jQuery
// Add span tag, if not set
$(document).ready(function(c) {
$('div#content ul.tabs li a').each(function(c){
// Add span wrapper if not there already
if( $(this).html().indexOf('span') == -1){
$(this).html('<span class="tab">' + $(this).html() + '</span>');
}
});
});
DT
Try to implement this
function function1() {
var m = document.all.myDiv.contains(myB);
if (m == true){
m = "YES"
} else {
m = "NO"
}
alert(m)
}