如何在文本中检测反引号(`)并在javascript中使用代码标记进行换行

时间:2018-05-23 10:05:34

标签: javascript

有没有办法检查文本中的反引号(`)并将其替换为javascript中的<code>

例如:

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

这里它应该检测`并且应该用<code>标签替换。输出应为:

Hello <code>@James P. Pauli</code>, How r you.

2 个答案:

答案 0 :(得分:1)

您可以使用String.replace。另请查看regex lookahead, lookbehind and atomic groups

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

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

console.log(text);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

使用replaceregex轻松完成此操作!

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

若您可能有多次出现:

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