How to make an expression of the following form:

text.replace(new RegExp('< здесь может быть один или несколько пробелов или ни одного' + vars + 'здесь может быть один или несколько пробелов или ни одного, а здесь может быть какое то содержимое или ничего, здесь может быть один или несколько пробелов или ни одного, ну а здесь всё что угодно кроме / или нечего, сдесь тоже может быть один или несколько пробелов или нечего>', 'gim'), '<br $3 />'); 

For example, tried this:

 var vars = "br"; text.replace(new RegExp('<[\s+]?' + vars + '[\s+]?([^<]*)?[\s+]?[^\/][\s+]?>', 'gim'), '<hr $3 />'); 

Did not work out. Here are some lines to change:

 < br class="hr" > на <hr class="hr" /> < br class="hr" > на <hr class="hr" /> < br > на <hr /> <br > на <hr /> <br> на <hr /> 

and other options.

    2 answers 2

     var str = '<br>'; var pat = /<\s*(\S+)\s*([^>]*)>/gi; str.replace(pat, '<$1 $2 />').replace(/\s+/g, ' '); 

    Instead of (\S+) and $1 you can write br and hr respectively - there will be your option.

    • Of course I have already done it myself)))) but your version also works)))) - shol

    They say the regular season can be written absolutely any, but it may be easier to do by splitting the task into parts.

    For example, first remove the spaces after the opening tag " < ". Something like this, for example:

     text.replace(new RegExp(/<\s+/gim,'<'); 

    Next, get rid of the spaces at the end of the tag " > " and replace it accordingly with "/>"

     text.replace(new RegExp(/\s+>/gim,' />'); 

    You can now remove extra spaces in the inside.

     text.replace(new RegExp(/\s+/gim,' '); 

    Well, actually replace any phrase with the necessary

     var patt = "br"; var rep = "hr" text.replace(new RegExp(patt, 'gim'), rep); 

    You can also wrap it all in a function for convenience. I did not test it myself, but I think the direction of thought is understandable.

    In addition, I can advise this resource http://gskinner.com/RegExr/ , where you can play regular games with live. I happen to use this service to work with text, because editors rarely provide the necessary search / replace. And to write utilities for a long time.