I to replace dot(.)
into special character "।"
on only dot(.)
keypress.
I don't have much knowledge of coding.
I found a function, but when I paste a text file in the text area, it replaces all dots that are present in a text file into special characters "।"
.
If I am wrong, please edit or suggest the appropriate code in the code.
<!doctype html>
<html dir='ltr' lang='en-GB'>
<head>
<meta charset="UTF-8">
<title>test page</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function() {
$('textarea').on("keyup", function(e) {
var val = $(this).val();
var str = val.replace('.', '।');
$(this).val(str);
});
});
</script>
</head>
<body>
<textarea></textarea>
</body>
</html>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
To replace last .
just key in. It does not handle the case when pressing dot and hold.
$(function() {
$('textarea').on("keyup", function(e) {
if (e.key === '.') {
const index = this.selectionStart;
const text = $(this).val();
if (index > 0 && text.charAt(index - 1) === '.') {
$(this).val(text.substr(0, index - 1) '|' text.substr(index));
this.selectionStart = index;
this.selectionEnd = index;
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea></textarea>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Replacing the last character if the input was a dot should fix it:
$(this).val($(this).val().replace(/.$/,"|"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function() {
$('textarea').on("keydown", function(e) {
if(e.key==='.'){
e.preventDefault();
$(this).val($(this).val().substring(0, $(this).val().length - 1) '|');
/*let inputVal = $(this).val();
inputVal = inputVal.substring(0, inputVal.length - 1);
inputVal = inputVal '|';
$(this).val(inputVal);*/
}
});
});
</script>
<textarea></textarea>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>