简体   繁体   English

正则表达式不能在“ JavaScript字符串内”工作

[英]regex not working “within” javascript string

I'm trying to replace all mentions of [b] in a text string and replace it with <b> . 我正在尝试替换文本字符串中对[b]的所有提及,并替换为<b> The problem with what I'm using below this that it's replace every [b] on the page, and I only want it to change the [b]'s within the text string ("text") that I'm sending in. 我在此下方使用的问题是替换页面上的每个[b],而我只希望它更改我要发送的文本字符串(“ text”)中的[b]。

Taking out the 'g' for global in the regex doesn't work very well because it then doesn't replace them all... 在正则表达式中为全局变量取出'g'并不能很好地工作,因为这样就不能全部替换它们...

text = $("#input").val();

text = text.replace(new RegExp('(^|\\s|>)\\[b](\\S.*?\\S)\\[/b]($|\\s|<)', 'gim') , '$1<strong>$2</strong>$3');

any ideas? 有任何想法吗? Thanks 谢谢

I'm not exactly sure what the problem is because the question is a bit unclear. 我不确定是什么问题,因为这个问题还不清楚。 Are you trying to replace the content within the textarea with the new html tags? 您是否要使用新的html标签替换textarea中的内容?

The following code is currently working for me in production: 以下代码目前正在生产中为我工作:

text = $("#contract_body").val();  // strore the current contents
text = text.replace(/\[b\](.*?)\[\/b\]/gim, "<strong>$1</strong>");  // replace bbcode with html tags
$("#contract_body").val(text);  // update the textarea with the new string contents

I hope that helps. 希望对您有所帮助。

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

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