JavaScript regexp全局选项不起作用(正如我所期望)

时间:2014-05-04 20:48:17

标签: javascript regex

考虑

a = '<img src="one.png" alt="One"> <img src="two.png" alt="Two">' + "\n" + 
    '<img src="thr.png" alt="Thr"> <img src="fou.png" alt="Fou">'
i = '/a/b/c/d/blah'
b = a.replace(/<img src="(.*)"(.*)>/g, '<img src="' + i + '/$1"$2>')

结果

'<img src="/a/b/c/d/blah/one.png" alt="One"> <img src="two.png" alt="Two">\n<img src="/a/b/c/d/blah/thr.png" alt="Thr"> <img src="fou.png" alt="Fou">'

鉴于/g选项,我真的期望(并希望)src的四个实例的所有实例都以i的值为前缀。我的错是什么?

2 个答案:

答案 0 :(得分:4)

我认为.*是贪婪的,所以它一直持续到它找到最后一次出现的内容为止。 如果你添加?,它就不会贪婪。 所以 -

/<img src="(.*?)"(.*?)>/g

或者您可以更具体(任何不是"及以后的字符,任何不是>的字符) -

/<img src="([^"]*)"([^>]*)>/g

(或两者)

答案 1 :(得分:1)

请改为尝试:

a = '<img src="one.png" alt="One"> <img src="two.png" alt="Two">' + "\n" + 
    '<img src="thr.png" alt="Thr"> <img src="fou.png" alt="Fou">'
i = '/a/b/c/d/blah'
b = a.replace(/<img src="(.*?)"(.*?)>/g, '<img src="' + i + '/$1"$2>');

<强> 说明:

Match the characters “<img src="” literally «<img src="»
Match the regular expression below and capture its match into backreference number 1 «(.*?)»
   Match any single character that is not a line break character «.*?»
      Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the character “"” literally «"»
Match the regular expression below and capture its match into backreference number 2 «(.*?)»
   Match any single character that is not a line break character «.*?»
      Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the character “>” literally «>»
相关问题