首页 > 解决方案 > 替换()正则表达式多个换行符字符串不起作用javascript

问题描述

我有下一个字符串 bbcode 类型[MSG]abc[/MSG],我想用一个友好的字符串替换它......使用正则表达式

当 bbcode 仅在第一行时,我的代码有效,但是当我在[MSG]带有换行符的标签中放置更多文本时......它不起作用......

做错了什么?

编码尝试

$("button").on("click", function(){
var textarea = $("#textarea").val();
 var regex = /\[MSG\](.*)\[\/MSG]/ig;

   
   textarea = textarea.replace(regex,"converted: $1 --");
   

$("div").text(textarea)

})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>

hello [MSG]abc[/MSG]
<HR>
hello [MSG]a <BR>

bc[/MSG]
<HR>
<textarea id='textarea' rows=3>
hello [MSG]abc[/MSG]
/
hello [MSG]a 

bc[/MSG]

</textarea>

<button>convert</button>
<div></div>

标签: javascriptjquery

解决方案


您应该使用添加了 s 开关的单行模式正则表达式:

正则表达式 = /[MSG](.*?)[/MSG]/igs;

在正则表达式中,点匹配除换行符 \n 之外的每个字符。使用单行开关,所有换行符都集成到一个字符串中。

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>

hello [MSG]abc[/MSG]
<HR>
hello [MSG]a <BR>

bc[/MSG]
<HR>
<textarea id='textarea' rows=3>
hello [MSG]abc[/MSG]
/
hello [MSG]a 

bc[/MSG]

</textarea>

<button>convert</button>
<div></div>

<script>
$("button").on("click", function(){
   var textarea = $("#textarea").val();
   var regex = /\[MSG\](.*?)\[\/MSG]/igs;

   textarea = textarea.replace(regex, "converted: $1 --");

   $("div").text(textarea)

})
</script>

本文可能是阅读https://www.regular-expressions.info/dot.html的良好开端

$("button").on("click", function(){
   var textarea = $("#textarea").val();
   var regex = /\[MSG\](.*?)\[\/MSG]/igs;
   
   textarea = textarea.replace(regex, "converted: $1 --");
   
   $("div").text(textarea)

})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
hello [MSG]abc[/MSG]
<HR>
hello [MSG]a <BR>

bc[/MSG]
<HR>
<textarea id='textarea' rows=3>
hello [MSG]abc[/MSG]
/
hello [MSG]a 

bc[/MSG]

</textarea>

<button>convert</button>
<div></div>


推荐阅读