Monday, 8 January 2018

javascript - Check whether a string matches a regex in JS

You can use match() as
well:



if
(str.match(/^([a-z0-9]{5,})$/)) {

alert("match!");
}



But
test() seems to be faster as you can read href="https://stackoverflow.com/a/10940138/1895428">here.



Important
difference between match() and
test():



match()
works only with strings, but test() works also with
integers.



12345.match(/^([a-z0-9]{5,})$/);
// ERROR
/^([a-z0-9]{5,})$/.test(12345); //
true
/^([a-z0-9]{5,})$/.test(null); //
false


// Better watch out for undefined
values
/^([a-z0-9]{5,})$/.test(undefined); //
true

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...