问题描述
我有这个图片网址:http://files.myweb.com/12/06/002_xz808/normal_paris_01.jpg
我需要得到这个 http://files.myweb.com/12/06/002_xz808/paris_01.jpg
我不能在 "normal_"
上使用简单的替换功能,因为这个关键字可能会意外地出现在其路径中的文件名之前.我需要将它用于 THE LAST "normal_"
但我不知道如何使用.请帮忙.
I can't use simple replace function on "normal_"
because this keyword can accidentaly appear before filename in its path. I need to use it for THE LAST "normal_"
but I don't know how. Please help.
推荐答案
希望对您有所帮助:
function replNormal(normal) {
return normal.replace(/^(.*)normal\_(.*?)$/, '$1$2');
}
console.log(replNormal("http://files.myweb.com/12/06/normal_002_xz808/normal_paris_01.jpg"));
前面的正则表达式中的捕获组(括号中的部分)先贪婪后懒惰.
The capture groups in the prior regular expression (the parts in parenthesis) are greedy and then lazy.
贪婪的 (.*) 希望在停止捕获之前尽可能地扩展.
The greedy one (.*) wants to expand as far as it can, before it stops capturing.
懒人 (.*?) 希望在满足捕获要求时尽快退出.
The lazy one (.*?) wants to quit as quickly as it meets it's capture requirements.
替换字符串中的反向引用告诉它直接将在第一个和第二个捕获组中找到的内容连接在一起,跳过未捕获的正常_
The back references in the replacement string tell it to concatenate what it finds in the first and second capture groups directly together, skipping the non-captured normal_
这篇关于Javascript 匹配从 URL 中删除部分文件名 - 替换最后一次出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!