Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 302
max Avatar asked Mar 06 '26 10:03

max


1 Answers

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>
like image 134
jacouh Avatar answered Mar 08 '26 00:03

jacouh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!