How to use Regular Expression In Javascript
The Regular Expression approach for checking prime numbers in JavaScript involves testing if the number is a prime using a regular expression pattern. The pattern `/^1?$|^(11+?)\1+$/` evaluates true if the number is prime and false otherwise.
Example: In this example we are following above explained apporach.
function isPrimeRegExp(num) {
return !/^1?$|^(11+?)\1+$/.test('1'.repeat(num));
}
console.log(isPrimeRegExp(17)); // Output: true
console.log(isPrimeRegExp(3)); // Output: true
console.log(isPrimeRegExp(8)); // Output: false
console.log(isPrimeRegExp(15)); // Output: false
Output
true true false false
Check a number is Prime or not using JavaScript
We are given a positive integer N and the task is to find out whether the given number is prime or not. A prime number is a number that is divisible by 1 and itself only.
Examples:
Input: N = 4 Output: Not Prime Explanation: The given number 4 is also dividble by 2 other than 1 and itself. Input: 5 Output: Prime Explanation: 5 can only be divisible by 1 and itself.
These are the following ways to solve this problem:
Table of Content
- Checking prime number using Flag variable
- Using the root value of given number
- Using recursive approach
- By reducing iterations in the loop
- Using Regular Expression
Contact Us