简体   繁体   中英

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;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM