0

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>);
Sarvesh Mahajan
  • 914
  • 7
  • 16
Skoby
  • 161
  • 1
  • 2
  • 10

3 Answers3

1

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

aloisdg
  • 22,270
  • 6
  • 85
  • 105
  • thanks but this will print the text with the tags: I have this text and want this part to be bold . Maybe is it because I'm working with jsx – Skoby Jan 07 '20 at 12:32
  • @Eskoby Add the tag jsx to your question. You never mentioned it until now. By the way, do you plan to support bbcode or only the `[b]` tag? – aloisdg Jan 07 '20 at 13:13
0

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)
Pushprajsinh Chudasama
  • 7,772
  • 4
  • 20
  • 43
0

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);
  • not working for me...eslint is complaining regarding the redundant character escape. – Skoby Jan 07 '20 at 12:36
  • ignoring the redundant character escape, it will print the text without interpreting the tag – Skoby Jan 07 '20 at 12:45
  • function main(str) { str = str.replace(/\[b\](.*?)\[\/b\]/ig, '$1'); return str; } var str = 'I have this text [b] and want this part to be bold [/b].'; main(str); I checked with JShint.com and it shows no error or warning :- There is only one function in this file. It takes one argument. This function contains 2 statements. Cyclomatic complexity number for this function is 1. – Koushik Basu Jan 08 '20 at 04:44