简体   繁体   中英

Regular Expression to get a number between two strings in Javascript

Here are samples:

  • example 1: string1<span id="header">5655811</span>string2
  • example 2: string3<span id="header">51481</span>string4
  • example 3: string5<span id="header">854211</span>string6

How can I get the number between <span id="header"> and </span> with JavaScript regex?

It depends on how safe you want to be. If you're sure that all of your input looks exactly like you have in your message, you can use:

var n = Number( input.match( /<span id="header">(\d+)<\/span>/ )[1] );

A slightly safer version would be:

var n;
var match = input.match( /<span id="header">\s*(\d+)\s*<\/span>/ );
if( match ) {
    n = Number( match[1] );
} else {
    // do error handling here
}

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