How to check if string contains only digits in JavaScript ?
Given a string and the task is to check whether it contains only digits or not.
JavaScript test() Method: This method tests for a pattern in a string. This method returns true if match is found, otherwise it returns false.
Syntax:
RegExpObject.test(str)
Parameters: This function accepts single parameter str which is required. It specifies the string which to be searched.
Example 1: This example checks for the non-digit string by using RegExp.
<!DOCTYPE HTML> < html > < head > < title > Check if string contains only digits </ title > </ head > < body style = "text-align:center;" id = "body" > < h1 style = "color:green;" > GeeksForGeeks </ h1 > < p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;" > </ p > < button onclick = "gfg_Run()" > check </ button > < p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;" > </ p > < script > var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var path = "4323424242"; el_up.innerHTML = "String = '"+path + "'"; function gfg_Run() { el_down.innerHTML = /^\d+$/.test(path); } </ script > </ body > </ html > |
chevron_right
filter_none
Output:
-
Before clicking on the button:
-
After clicking on the button:
Example 2: This example checks for the non-digits string by using RegExp.
<!DOCTYPE HTML> < html > < head > < title > Check if string contains only digits </ title > </ head > < body style = "text-align:center;" id = "body" > < h1 style = "color:green;" > GeeksForGeeks </ h1 > < p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;" > </ p > < button onclick = "gfg_Run()" > check </ button > < p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;" > </ p > < script > var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var path = "+4323424242"; el_up.innerHTML = "String = '"+path + "'"; function gfg_Run() { el_down.innerHTML = !/\D/.test(path); } </ script > </ body > </ html > |
chevron_right
filter_none
Output:
-
Before clicking on the button:
-
After clicking on the button: