Заменить некоторую подстроку тегами html - PullRequest
1 голос
/ 04 мая 2020

Привет У меня есть строка, как показано:

var testStr = 'Soft is a texture, I am soft spoken and I like softy ice cream';

Хотите добавить теги 'span' вокруг слова 'soft': Таким образом, результатом может быть:

<span class='add-some-style'>Soft</span> is a texture, I am <span class='add-some-style'>soft</span> spoken and I like <span class='add-some-style'>soft</span>y ice cream

Пробная строка. заменить, но безуспешно.

Ответы [ 3 ]

2 голосов
/ 04 мая 2020

Вы можете использовать Regex для замены. Выполните глобальный поиск, игнорируя регистр. Замените соответствующий шаблон вместе с дополнительными тегами.

var testStr = 'Soft is a texture, I am soft spoken and I like softy ice cream';
var strVariable = 'soft'
var regexValue = new RegExp( `(${strVariable})`, 'ig');
const newStr = testStr.replace(regexValue, "<span class='add-some-style'>$1</span>");

console.log(newStr);
1 голос
/ 04 мая 2020

Вы можете нарезать html каждый раз, когда находите мягкое ключевое слово, а затем использовать конкатенацию, чтобы получить свой результат

var testStr = 'Soft is a texture, I am soft spoken and I like softy ice cream';
let index = 0;
let acc = '';
const wordLength = 4;

while (index >= 0) {
  const softWord = testStr.substr(index, wordLength);
  const preText = testStr.substring(0, index);
  acc += preText + '<span class="add-some-style:>' + softWord + '</span>';
  testStr = testStr.substring(index + wordLength);
  index = testStr.toLowerCase().indexOf('soft')
}
console.log(acc + testStr)
1 голос
/ 04 мая 2020

Вы можете использовать регулярные выражения и строки заменить

var testStr = 'Soft is a texture, I am soft spoken and I like softy ice cream';
const newStr = testStr.replace(/^Soft/gi, '<span class="highlight">Soft</span>');

document.getElementById('test').innerHTML = newStr;
.highlight {
  color: green;
}
<div id='test'></div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...