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'));
Related
Why does this not work for finding if a string includes a letter and then returning false?
And how can I do it?
return pin.includes(/[a-z]/) ? false : true
Because there includes takes a string in it's argument.
In your case you can use match, or test
Example:
var regExp = /[a-z]/;
regExp.test('some text'); // return true
Example 2:
'some text'.match(/[a-z]/);
'123'.match(/[a-z]/); // return null
includes() doesn't take regex. Try match() instead.
let pin = "hello";
console.log(!pin.match(/[a-z]/)); //"!" inverts result to match your logic
pin = "132";
console.log(!pin.match(/[a-z]/));
And because the return value from match() is truthy or falsy, you don't need the ternary if/else you used in your example.
You need to use the String.prototype.match(regex) function.
const reg = /[a-zA-Z]/
const func = (s) => !s.match(reg);
console.log(func("465496464[][]"));
console.log(func("4464644aa423164646"));
You can use regex test method. Test method tests for a match in a string and it returns true if it finds a match and false otherwise.
const pin = 'abc123';
const ret = !/[a-zA-Z]/g.test(pin);
console.log(ret);
Try this:
var r = new RegExp(“[a-zA-Z]”);
return r.test(pin);
With “pin” being a string variable.
I have a variable which contain a string and I want to return only the letters from regular expression (“b” and “D”) or any letter that I indicate on regular expression from match().
var kk = "AaBbCcDd".match(/b|D/g);
kk.forEach(function(value,index){
console.log(value,index)
});
My problem is that regular expression I think because is returning b and D but the index is not the index from kk variable and I'm not really sure, why ... so if someone can help me a little bit because I stuck
The match method from javascript only returns an array with the given match:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/match
You would need to implement a new function which will loop through all characters of your string and return the given index of the matches.
This method could use the function search from String.prototype: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/search
You have to write a new function to get the index of the matched regex like a sample below:-
var re = /bar/g,
str = "foobarfoobar";
while ((match = re.exec(str)) != null) {
alert("match found at " + match.index);
}
Hope this will help you
Actually this is the answer :
var kk = "AaBbCcDd".match(/B?d?/g);
kk.forEach(function(value,index){
console.log(value,index)
});
if someone will encounter this scenario ...
The match() regular expresion B?d? will return an array indicating the position of "B" and "d" of the initial array kk.
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'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;
}
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');