天天看点

js截取两个字符串之间match方法(正则表达式)

首先我想截取

http://219.234.155.200:6528/api/v1/icon/11001000040/sprite 

这个字符传中的icon后面,sprite前面的,不带"/" 的id

我们首先要确定的是"/" 在正则中的表示方法/\//

var str = 'http://219.234.155.200:6528/api/v1/icon/11001000040/sprite '

str .match(/icon\/(\S*)\/sprite/)[1]

var str = 'http://219.234.155.200:6528/api/v1/icon/11001000040/sprite '
console.log(str.match(/icon\/(\S*)\/sprite/)[1],"截取中间值",str.match(/(\S*)\/sprite/)[1],"截取前面的值",str.match(/icon\/(\S*)/)[1],"截取后面的值")
//输出值   11001000040 截取中间值 http://219.234.155.200:6528/api/v1/icon/11001000040 截取前面的值 11001000040/sprite 截取后面的值
           

下面说下数量词

(?=)这表示以ff结尾的前面的字符串,但不包括=号后面的

(=?)这表示以iid开头的字符串,但不包括=号前面的

var str = 'http://219.234.155.200:6528/api/v1/icon/11001000040/sprite '
console.log(str.match(/icon\/(\S*)\/sprite/),"截取中间值")
console.log(str.match(/(\S*)(?=\/sprite)/),"截取前面的值")
console.log(str.match(/(icon\/=?)(\S*)/),"截取后面的值")
           
js截取两个字符串之间match方法(正则表达式)

继续阅读