NastyDiaper
NastyDiaper

Reputation: 2558

Javascript stripping out substring and appending it

I am trying to do something which should be simple but I'm having no luck. I have a string like the following:

<hgc attr="something">late at</hgc>

and I need to strip out the last at prior to the closing html tag and append it, surrounded by its own tag to produce:

<hgc attr="something">late </hgc><hgb>at</hgb>

Don't worry about the tags, they are custom.

Update

That at word may be anything, even hgc and I will already have the word ahead of time to produce the appended html.

I have attempted to perform the following:

let markup = '<hgb>' + word + '</hgb>';

let applied = $element.html().slice(0, pos) + 
                  $element.html().slice(pos).replace(word, "") +
                  markup;

Upvotes: 0

Views: 40

Answers (1)

Tsubasa
Tsubasa

Reputation: 1429

Try this one.

let str = '<hgc attr="something">late at</hgc>';
let reg = /\w+(?=<)/g;

let word = str.match(reg)[0];
str = `${str.split(reg).join('')}<hgb>${word}</hgb>`;

console.log(str);

Something like this should work.

Upvotes: 2

Related Questions