简体   繁体   中英

Regex to replace text between (outside) two tags

I am trying to use some regex to wrap the word "or" in a <span> tag in some markup.

<div id="test">
  <a href="#" class="thickbox open-details-modal" aria-label="View version 1.5.29 details">View version 1.5.29 details</a> or <a href="#" class="update-link" aria-label="Update now">update now</a>
</div>

<div id="result"></div>
var html = $( '#test' ).html();

html = html.replace( /(<\/a>[\s\S]*?<a)/, "<\/a><span class='or'>$1<\/span><a href" );

$( '#result' ).html( html );

The resulting markup is a bit strange:

<div id="result">
  <a href="#" class="thickbox open-details-modal" aria-label="View version 1.5.29 details">View version 1.5.29 details</a><span class="or"> or <a< span=""><a href="" class="update-link" aria-label="Update now">update now</a>
</a<></span></div>

The result nests the second <a> inside of the ` element. I can't seem to wrap my head around why it's nesting in such a weird way.

<span class="or"> or <a< span=""><a href="" class="update-link" aria-label="Update now">update now</a>
</a<></span>

I've got a fiddle where I was testing some things here: https://jsfiddle.net/qfuLozxw/

Intended results:

<div id="test">
  <a href="#" class="thickbox open-details-modal" aria-label="View version 1.5.29 details">View version 1.5.29 details</a> <span class="or">or</span> <a href="#" class="update-link" aria-label="Update now">update now</a>
</div>

The content matched inside your parenthesis is what gets returned in the $1 variable. You just need to contain the text you want to replace:

html = html.replace( /<\/a>( or )<a/, "<\/a><span class='or'>$1</span><a" );

Or if you want to match on any word inbetween your links:

html = html.replace( /<\/a>( \w* )<a/, "</a><span class='or'>$1</span><a" );

Example is here: https://jsfiddle.net/wbard38q/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM