1

Hi I have a string as shown:

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

Want to add 'span' tags around word 'soft': So result could be:

<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

Tried string.replace, but with no success.

1
  • 6
    could you show the code you tried? Commented May 4, 2020 at 16:50

3 Answers 3

2

You can use Regex to replace. Do a global search while ignoring the case. Substitute the matched pattern along with extra tags.

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);

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the reply, but if I want variable in regex, then?
1

You can use regex & string replace

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>

1 Comment

Have accepted one answer but increased points for all the answers, they gave insight for me to think. Thanks.
1

You can slice the html every-time you find the soft keyword and then use concatenation to get your result

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.