首页 > 解决方案 > 如何知道插入符号的位置是否在文本框中的 {} 字符之间?

问题描述

我有一个可能包含任何字符串的文本框。假设文本框中的当前值为

Testing {0} behaviour.

我想知道当前插入符号的位置(在单击文本框或输入值期间)是否在两个大括号('{'和'}')之间,如果是,我想知道大括号内的内容集.

注意:字符串中可能还设置了多个花括号。例如 -

Testing {0} behaviour of {1} iterations

如果光标位于任何花括号集中,我希望函数返回 true 和相应的整数(0 或 1)。

我可以使用以下方法获取当前光标位置:- 文本框elem.selectionStart在哪里elem。正则表达式不是我的强项,这就是我在这里遇到困难的原因。我相信可以使用长字符串操作逻辑来做到这一点,但我正在尝试找到一个优雅的解决方案。

标签: javascripthtmlregex

解决方案


我们只需要匹配里面只有整数的花括号。

您可以使用/\{(\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>


推荐阅读