简体   繁体   English

替换所有特殊字符的实例

[英]Replace all instances of special character

 var whatever = 'Some [b]random[/b] text in a [b]sentence.[/b]';

How can I replace every instance of [b] with <b> and every instance of [/b] with </b> in jQuery? 如何可以替换的每一个实例[b]<b>和的每一个实例[/b]</b> jQuery中?

I was attempting to do it with regex but I couldn't get it to function properly. 我试图用正则表达式来做这件事,但我无法让它正常运行。

Elegant way: 优雅的方式:

whatever = whatever.replace(/\[(\/?)b\]/g,'<$1b>');

See and test it here . 在这里查看并测试它。

With regex, it'd be: 使用正则表达式,它将是:

whatever = whatever.replace(/\[b\]/g,'<b>').replace(/\[\/b\]/g,'</b>');

That'd seem to be the easiest solution 这似乎是最简单的解决方案

string.replace("[b]", "<b>");

如果失败了,如果将它上传到数据库,你可以使用PHP来使用str_replace来完成它。

whatever = whatever.replace(/\[b\]/g, '<br>').replace(/\[\/b\]/g, '</b>');

DEMO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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