Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a word begins with a vowel?

So I have a basic js query, let's say I have

document.getElementById('test').value();

Inside this value is the word "Idea".

How can I create a function which checks if this begins with I, or any vowel? In the simplest way possible?

like image 922
user9163418 Avatar asked Aug 30 '25 17:08

user9163418


2 Answers

You can use regular expressions ^[aieouAIEOU].* to check if it starts with vowel.

http://jsfiddle.net/jpzwtm3f/1/

var testStr = 'Eagle'
var vowelRegex = '^[aieouAIEOU].*'
var matched = testStr.match(vowelRegex)
if(matched)
{
alert('matched');
}
else
{
alert('not matched');
}
like image 152
Muhammad Ramzan Avatar answered Sep 02 '25 07:09

Muhammad Ramzan


Referring to what Muhammad pointed out.

You can use a regex like so /^[aeiou].*/i.

  • Caret ^ = beginning of the string
  • [aeiou] = match any character inside brackets
  • .* = match any amount of characters after [Greedy]
  • i = case-insensitive

function testVowels(e) {
  const regex = new RegExp('^[aeiou].*', 'i');
  let inputVal = $(e.target).val();
  let regexOutput = regex.test(inputVal);
  
  // If is true
  if(regexOutput) {
    $('#debug').text("Test: True");
  } else {
    $('#debug').text("Test: False");
  }
}
span {
  color: red;
  font-size: 12px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Type something:<hr>
<input type="text" onkeyup="testVowels(event)" /><br>
<span id="debug"></span>
like image 42
Alex Avatar answered Sep 02 '25 06:09

Alex