0

My requirement to return true or false based on checking whether a string is single word with only Alphabets in it.

I tried following:

<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction(){
document.getElementById("demo").innerHTML = /[a-zA-Z]+/.test("Hello123");
}
</script>

But this is returning me true instead of expected false

Am I using regexObject.test( String ) in wrong way ?

Om Sao
  • 7,064
  • 2
  • 47
  • 61

2 Answers2

2

You need to check if the string starts (^), ends ($) and contains only letters:

console.log("Hello123", /^[a-zA-Z]+$/.test("Hello123"));

console.log("Hello", /^[a-zA-Z]+$/.test("Hello"));
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
2

You need a start symbol ^ and an end symbol $ as well for checking the whole string.

document.getElementById("demo").innerHTML = /^[a-zA-Z]+$/.test("Hello123");
<p id="demo"></p>

You could shorten the regular expression with insensitive flag.

document.getElementById("demo").innerHTML = /^[a-z]+$/i.test("Hello");
<p id="demo"></p>
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392