Существует ли версия String.indexOf JavaScript (), который допускает регулярные выражения?

Используйте each для итерации по каждому .btn. Например, если вы хотите добавить текст заголовка к существующей кнопке:

$('.btn').each(function() {
  $(this).text( $(this).text() + ' --- ' + $(this).prop('title') );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="btn" title="Title Text 1">Button Text 1</button>
<button class="btn" title="Title Text 2">Button Text 2</button>
<button class="btn" title="Title Text 3">Button Text 3</button>

201
задан Ned Batchelder 8 November 2008 в 05:19
поделиться

1 ответ

Я использовал String.prototype.match(regex), который возвращает строковый массив всех найденных совпадений данного regex в строке (дополнительную информацию см. Здесь ):

function getLastIndex(text, regex, limit = text.length) {
  const matches = text.match(regex);

  // no matches found
  if (!matches) {
    return -1;
  }

  // matches found but first index greater than limit
  if (text.indexOf(matches[0] + matches[0].length) > limit) {
    return -1;
  }

  // reduce index until smaller than limit
  let i = matches.length - 1;
  let index = text.lastIndexOf(matches[i]);
  while (index > limit && i >= 0) {
    i--;
    index = text.lastIndexOf(matches[i]);
  }
  return index > limit ? -1 : index;
}

// expect -1 as first index === 14
console.log(getLastIndex('First Sentence. Last Sentence. Unfinished', /\. /g, 10));

// expect 29
console.log(getLastIndex('First Sentence. Last Sentence. Unfinished', /\. /g));
0
ответ дан 23 November 2019 в 05:04
поделиться
Другие вопросы по тегам:

Похожие вопросы: