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?
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');
}
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With