0

Is there any way to check backtick (`) in text and replace it with <code> in javascript.

For example:

var text = "Hello `@James P. Pauli`, How r you.";

Here it should detect the ` and should be replace with <code> tag. Output should be this:

Hello <code>@James P. Pauli</code>, How r you.
eisbehr
  • 12,243
  • 7
  • 38
  • 63

2 Answers2

2

Use replace and regex to do this easily!

var text = "Hello `@James P. Pauli`, How r you.";
text = text.replace(/`(.*)`/, '<code>$1</code>');
console.log(text);

Of if you may have multiple occurrences:

var text = "Hello `@James P. Pauli`, How r `you`.";
text = text.replace(/`(.*?)`/g, '<code>$1</code>');
console.log(text);
eisbehr
  • 12,243
  • 7
  • 38
  • 63
1

You can use String.replace. Also have a look at regex lookahead, lookbehind and atomic groups

var text = "Hello `@James P. Pauli`, How r you.";

text = text.replace(/`((?!`).+)`/g,'<code>$1</code>');

console.log(text);
Thum Choon Tat
  • 3,084
  • 1
  • 22
  • 24