Reputation: 1018
I am working on a project where I want to capitalize each word, as you type in textarea on keypress event. Now, I am starting with just few words such as SELECT
, FROM
and WHERE
, which is by-default known as reserved word in MySQL.
I have created an array where I store this words. But now the problem I am facing here is how to get the whole word as you type the letters.
I have got few help from fellow stackoverflow threads, but I am unable to get any kind of help to get the value of whole word as you type the letters.
Example:
Original string will be like this
select name from accounts where id = '123'
and as you type above string, the result should be like this
SELECT name FROM accounts WHERE id = '123'
Till now, I am able to capitalize the only one word in textarea, but I couldn't do it when I try to enter the whole sql. Below find the code, which I am using
$("#test").keyup(function () {
var arr = ['SELECT', 'FROM', 'WHERE'];
for (var i in arr) {
if(arr[i].toUpperCase().indexOf($(this).val().toUpperCase()) == 0){
$(this).val($(this).val().toUpperCase());
break;
}
}
});
Upvotes: 0
Views: 453
Reputation: 23738
You can use word bourdaries \b
with regular expression and use the input
even to detect the copy paste of string
$("#test").on('input', function() {
var arr = ['SELECT', 'FROM', 'WHERE'];
let elem = $(this);
for (var i = 0; i < arr.length; i++) {
let regex = new RegExp('\\b(' + arr[i] + ')\\b', "gi");
elem.val(elem.val().replace(regex, arr[i]));
}
});
textarea {
width: 100%;
height: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="test"></textarea>
Upvotes: 0
Reputation: 171669
Split the string by spaces and map resultant array then join back with space
var $input = $("#test").on('input',function () {
var arr = ['SELECT', 'FROM', 'WHERE'];
$(this).val(function(_, currVal){
return currVal.split(' ').map(function(word){
return arr.includes(word.toUpperCase())? word.toUpperCase() : word;
}).join(' ')
})
})
// set value and trigger event for demo
$input.val("select name from accounts where id = '123'").trigger('input');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="test" style="width:100%">
Upvotes: 1
Reputation: 2875
You can use a regular expression (that ignores case) to replace all the words within val(), like so:
$("#test").keyup(function () {
var arr = ['SELECT', 'FROM', 'WHERE'];
for (var i in arr) {
// "i" ignores case and "g" makes the search global
var regEx = new RegExp(arr[i], "ig");
$(this).val($(this).val().replace(regEx, arr[i]));
}
});
Upvotes: 0