javascript - 如何知道插入符号的位置是否在文本框中的 {} 字符之间?
问题描述
我有一个可能包含任何字符串的文本框。假设文本框中的当前值为
Testing {0} behaviour
.
我想知道当前插入符号的位置(在单击文本框或输入值期间)是否在两个大括号('{'和'}')之间,如果是,我想知道大括号内的内容集.
注意:字符串中可能还设置了多个花括号。例如 -
Testing {0} behaviour of {1} iterations
如果光标位于任何花括号集中,我希望函数返回 true 和相应的整数(0 或 1)。
我可以使用以下方法获取当前光标位置:-
文本框elem.selectionStart
在哪里elem
。正则表达式不是我的强项,这就是我在这里遇到困难的原因。我相信可以使用长字符串操作逻辑来做到这一点,但我正在尝试找到一个优雅的解决方案。
解决方案
我们只需要匹配里面只有整数的花括号。
您可以使用/\{(\d+)\}/g
. (...)
在正则表达式中称为捕获组,您可以使用它来隔离重要信息,例如在这种情况下占位符的索引。
const elem = document.querySelector('textarea');
elem.addEventListener('keyup', feedback);
elem.addEventListener('click', feedback);
function feedback () {
const index = getIndex(this);
if (index === -1) console.log('no placeholder selected');
else console.log(`placeholder at index ${index} selected`);
}
function getIndex (element) {
const placeholder = /\{(\d+)\}/g;
const { value, selectionStart, selectionEnd } = element;
for (let match; (match = placeholder.exec(value)) !== null;) {
if (match.index < selectionStart && placeholder.lastIndex > selectionEnd) {
return Number(match[1]);
}
}
return -1;
}
<textarea>Testing {0} behaviour of {1} iterations</textarea>
推荐阅读
- hyperledger-fabric - Hyperledger Fabric fabcar 客户端无法连接到对等节点
- android - 异常 android.content.res.Resources$NotFoundException:来自可绘制资源 ID #0x7f0601d8 的文件 res/color/selector_tab_blue_white.xml
- uilabel - 在启用自动缩小到最小字体大小的情况下检测 UILabel 的点击
- nginx - 如果我没有域名,如何在 nginx 上将子文件夹设置为不同的根位置?
- meteor - 有没有办法从
- mysql - 优化包含范围表达式、排序依据和限制的 MySQL 查询时遇到问题
- c# - 使用 Newtonsoft JSON 反序列化十六进制值
- java - 如何在使用此依赖项目的 jar 对主应用程序进行 dockerizing 之前构建一个依赖项目?
- flutter - FutureBuilder Flutter 没有从我的计算中返回任何数据
- r - 如何匹配R中的字符变化