简体   繁体   中英

How can I replace characters with html tag? (enriching text)

Text = "I have this text [b] and want this part to be bold [/b]."

How can i replace the [b] and [/b] with strong html tag

so that the output is => I have this text and want this part to be bold .

I tried using lodash replace like this but eslint is complaining for the closing tag:

let startTag = _.replace(text, '[b]', <strong>);
let endTag= _.replace(startTag, '[/b]', </strong>);

Can you try to wrap <strong> with quote '<strong>' (same for the closing tag).

 let text = 'foo [b]bar[/b]'; let startTag = _.replace(text, '[b]', '<strong>'); let endTag = _.replace(startTag, '[/b]', '</strong>'); document.write(endTag);
 <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>

This markup look like BBCode . You may want to use an existing bbcode parser instead of building one. (check your favorite browser engine to find solution like Extendible-BBCode-Parser , js-bbcode-parser , node-bbcode , or even on Stack Overflow Convert BBcode to HTML using JavaScript/jQuery ).

If you don't want to use loadash then do like below.

 var text = "I have this text [b] and want this part to be bold [/b]." var openedTag = text.replace("[b]", "<strong>"); var closedTag = openedTag.replace("[/b]", "</strong>"); document.write(closedTag)

Simplest solution in java-script looks like this:

var str = 'I have this text [b] and want this part to be bold [/b].';
str = str.replace(/\[b\](.*?)\[\/b\]/ig, '<strong>$1</strong>');
console.log(str);

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