3

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>

2
  • You mean something like /\[MSG\]([^\]]*)\[\/MSG]/ig; or even /\[MSG\](.*|[\s\S]*)\[\/MSG]/ig ? Commented Apr 28, 2020 at 19:25
  • thank you. I think it fits, but which is the differente between them? Commented Apr 28, 2020 at 19:32

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

2 Comments

look good!!...a question what would be the difference between this regex and those ones provided as comment above? which one would avoid errors and syntax mistakes?
have you seen s switch added? /.../igs it makes difference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.