Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS replace regular expression but use part of the expression in the output like a variable

In making a simple bbcode parser, need to find within a string a substring like [color=blue] and replace it with something like <span style="color:blue">. I've been using regular expressions and javascript .replace() to do this. How can I use a regular expression to find what I need, but then also extract the color name to use in the span?

like image 764
user1755043 Avatar asked Nov 21 '25 04:11

user1755043


1 Answers

$(document).ready( function () {

    function my_func(whole_match, group1, group2) {
      return '<span style="' + group1 + ':' + group2 + '">';

    }

    var regex = /\[([^=]+)=([^\]]+)\]/;
    var str = 'hello [color=blue] world';
    var result = str.replace(regex, my_func);

  console.log(
      result
  );


});

--output:--
hello <span style="color:blue"> world
like image 155
7stud Avatar answered Nov 22 '25 18:11

7stud



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!