简体   繁体   中英

replace() regex multiple line break string not working javascript

I have the next string bbcode type [MSG]abc[/MSG] which I want to replace by a friendly string....using a regex

My code works when the bbcode is in the first line only, but when I put some more text within the [MSG] tag with line breaks....it doesnt work....

What am doing wrong?

CODED TRIED

 $("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>

You should use single line mode regex with s switch added:

regex = /[MSG](.*?)[/MSG]/igs;

In regex, dot matches every character except for newline \n. With the single line swtich, all newline characters are integrated into a single string.

<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>

This article might be a good beginning of reading 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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