Issue
let's assume an input string has given, for a particular character like '$' you want to add dynamically in the text field , so I want to find the index of a current character like '$' then it's not working properly like initially if I give '$'in any position, its reflection the position, example if I give 'random text$' it returns index 11 but if you type '$'in between text like 'random $text$' then it should return 7, but it returns 12,so by achieving 7 I need to give extra space like 'random $ text$', so dynamically how to get the index position of a current character($), whether It's added in first, middle, last of the text
let string = "random $text$";
let newArray = string.split("");
let store = string.length % 2 !== 0
? newArray.findLastIndex((x) => x === "$")
: newArray.findIndex((x) => x === "$");
console.log(store);
Solution
As you just want to add a space after first occurance of $
in the input string. You can simply achieve that by using String.replace()
method instead of looking for index
as If pattern
in replace function is a string, only the first occurrence will be replaced. The original string is left unchanged.
Live Demo :
function checkIndex(e) {
const val = e.target.value;
console.log(val.replace('$', '$ '));
}
<input type="text" id="val" onBlur="checkIndex(event)"/>
Update : Here is the workaround solution but not a good practice to do. For demo, I am using an input and after getting the index, I am replacing the $
with some other character so that I can get the index of current/newly added $
.
Demo :
function checkIndex(e) {
const val = e.target.value;
if (/$/.test(val)) {
console.log(val.indexOf('$'))
document.getElementById('val').value = val.replaceAll('$', '-')
}
}
<input type="text" id="val" onBlur="checkIndex(event)"/>
Answered By - Rohìt Jíndal
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.