如何动态获取输入文本中特定字符(如$)的正确索引位置?
问题描述
- 初始在任意位置输入
$时,能正常返回对应索引,例如输入random text$返回11; - 在文本中间输入多个
$(如random $text$),期望返回第一个$的索引7,但实际返回12; - 当前需要添加额外空格(如改为
random $ text$)才能得到正确的索引7。
现有JavaScript实现代码:
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);
解决方案
你的代码问题出在错误地将字符串长度的奇偶性作为判断依据,决定查找第一个还是最后一个$——这和你要获取第一个$索引的需求完全不相关。
要实现无论$位于文本开头、中间还是结尾,都能精准获取第一个出现的索引,直接使用JavaScript原生的String.prototype.indexOf()方法即可,无需拆分数组做多余处理:
let string = "random $text$"; // 获取第一个$的索引,若字符串中无$则返回-1 let firstDollarIndex = string.indexOf('$'); console.log(firstDollarIndex); // 输出7,符合预期
如果后续需要获取最后一个$的索引,可以用String.prototype.lastIndexOf():
let lastDollarIndex = string.lastIndexOf('$'); console.log(lastDollarIndex); // 输出12
针对文本框动态输入的场景,只需监听input事件,实时获取输入值并执行上述逻辑即可:
// 假设文本框的id为"text-input" const inputElement = document.getElementById("text-input"); inputElement.addEventListener("input", function() { const currentInput = this.value; const firstIndex = currentInput.indexOf('$'); console.log("第一个$的索引:", firstIndex); });
内容的提问来源于stack exchange,提问作者Sougata Mukherjee
相关产品推荐
相关产品推荐

