简体   繁体   中英

How to replace the last match of regex?

const spaceRegex = /<mspace\s+.*?\/>/
const answer = '<math xmlns="http://www.w3.org/1998/Math/MathML"><mi>h</mi><mfenced><mi>x<mspace linebreak="newline"/></mi></mfenced><mo>=</mo><semantics><mrow><mo>-</mo><mn>3</mn></mrow></semantics><mspace linebreak="newline"/><mi>D</mi><mo>=</mo><mi mathvariant="normal">&#x211D;</mi></math>'

I have a regex to match <mspace .... /> , there are two matches in the above answer. I want to replace the last match with <mspace width="10px"/>

So I want the output to be,

'<math xmlns="http://www.w3.org/1998/Math/MathML"><mi>h</mi><mfenced><mi>x<mspace linebreak="newline"/></mi></mfenced><mo>=</mo><semantics><mrow><mo>-</mo><mn>3</mn></mrow></semantics><mspace width="10px"/><mi>D</mi><mo>=</mo><mi mathvariant="normal">&#x211D;</mi></math>'

Regex is not a right way to deal with XML.
The better one is using DOMParser and XMLSerializer so you can traverse the DOM and update elements using DOM methods:

 const answer = '<math xmlns="http://www.w3.org/1998/Math/MathML"><mi>h</mi><mfenced><mi>x<mspace linebreak="newline"/></mi></mfenced><mo>=</mo><semantics><mrow><mo>-</mo><mn>3</mn></mrow></semantics><mspace linebreak="newline"/><mi>D</mi><mo>=</mo><mi mathvariant="normal">&#x211D;</mi></math>'; const D = (new DOMParser()).parseFromString(answer, "text/xml") const mspaces = D.getElementsByTagName('mspace'); mspaces[mspaces.length-1].outerHTML = '<mspace width="10px"/>'; const updated = (new XMLSerializer()).serializeToString(D); console.log(updated)
 .as-console-wrapper {top:0; max-height:none !important}

The regex solution is also available, but less reliable:

 const answer = '<math xmlns="http://www.w3.org/1998/Math/MathML"><mi>h</mi><mfenced><mi>x<mspace linebreak="newline"/></mi></mfenced><mo>=</mo><semantics><mrow><mo>-</mo><mn>3</mn></mrow></semantics><mspace linebreak="newline"/><mi>D</mi><mo>=</mo><mi mathvariant="normal">&#x211D;</mi></math>'; const updated = answer.replace(/(.*)<mspace[^/]+\\/>/, '$1<mspace width="10px"/>'); console.log(updated)
 .as-console-wrapper {top:0; max-height:none !important}

Hope this helps.

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