I learned that indexOf()
could not be used for searching the regular expression in the string, however search()
has not the start position and the end position as the optional parameters. How can I find and replace all certain regular expression in the same string? I added the problem where it is no so simple as replace()
will be enough.
Problem example
- Replace all consecutive two
<br/><br/>
with</p><p>
, if after second<br/>
some letters or digits (\w
) are following. - Leave all single
<br/>
of three or more consecutive<br/>
such as. - If there are no letter or digits after consecutive two
<br/><br/>
, leave it such as.
If we use replace()
for solving this problem, not only <br/><br/>
, but also following symbols will be replaced. To evade it, we need:
- Find the start of matching with regular expression. It will be
/(?:<br\s*[\/]?>){2}\s*\w+/
. - From the start of matching position, find the start position of
\w
part. - Replace the
/(?:<br\s*[\/]?>){2}\s*/
part with</p><p>
. - Repeat 1-3 inside the loop from the end of the previous matching position util next matches exists.
As I told above, I don't know how to search the new matching from the certain position. Is there some ways except slice the string and join it again?
var testString = $('#container').html();
console.log(testString.search(/(?:<br\s*[\/]?>){2}\s*\w+/));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<p>
<!-- Only one br: leave such as -->
Brick quiz whangs jumpy veldt fox! <br/>
<!-- Two br and letters then: replace by </p><p> -->
Sphinx of black quartz judge my vow! <br/><br />
<!-- No symbols after 2nd br: leave such as -->
Pack my box with five dozen liquor jugs. <br/><br /><br/>
<!-- Two br and symbols then: replace by </p><p> -->
The vixen jumped quickly on her foe barking with zeal. <br/><br />
<!-- No letters after <br/><br/>: leave such as -->
Brawny gods just flocked up to quiz and vex him.<br/><br />
<p>
</div>
` will be `\n\n`? – Takeshi Tokugawa YD May 09 '17 at 02:47