It is necessary to replace all occurrences of [br] in the headers h1 tag </br> . I am writing the following code:

 jQuery('h1').each(function() { var text = jQuery(this).text(); text.replace(/\[br]/g, '</br>'); jQuery(this).text(text); }); 

https://jsfiddle.net/cjq263ex/

Doesn't want to work, although the regular expression seems to be correct.

    2 answers 2

    There are a number of problems in your code:

    1. You are using the wrong regular expression. (Actually, you forgot to escape the character ] .) The correct regular expression looks like:

       /\[br\]/g 
    2. You do not replace correctly. The String.prototype.replace method returns the updated string, and does not make replacements in the current one.

    3. The jQuery.text method escapes all tags from the passed string, replacing the control characters with HTML entities. You need to use the jQuery.html method

    4. The br tag looks like <br /> and not </br> (note the position of the slash). Your version does not meet the standards, although it should work in browsers.

    Thus, the correct code is:

     jQuery('h1').each(function() { var text = jQuery(this).text(); text = text.replace(/\[br\]/g, '<br />'); jQuery(this).html(text); }); 

    JSFiddle with a working example.

    • Generally speaking I checked with the current expression - it works too. - Grundy
    • @Grundy, however, control characters are better escaped. Well, this is not the only problem in the TS code - Dmitriy Simushev
    • The .text () method does not cut anything; it escapes HTML code characters. - walik
    • @walik, you're right, updated the answer - Dmitriy Simushev
    • The character ] should be escaped only in a character class. There is no need to do this. It is necessary to screen only what is necessary to screen. - Wiktor Stribiżew

    replace returns a new string without changing the current one.

    This method does not change the String object on which it is invoked. It simply returns a new string.

    need to

     jQuery(this).text(text.replace(/\[br\]/g, '</br>')); 

    as noted by @walik, if you need to insert html instead of the text function, you need to use html

     jQuery(this).html(text.replace(/\[br\]/g, '</br>')) 
    • And the most important thing you forgot, the .text () method will output the html "as it is", you need to use .html () to make it work. - walik 1:09
    • @walik, added remark :-) - Grundy