[英]Replace part of URL using Regex Javascript
I'm trying to replace a part of the url with another string in javascript, so for example i have the following: 我正在尝试用javascript中的另一个字符串替换url的一部分,例如,我有以下内容:
res/icons/android/quickshop/icon-36-ldpi.png
res/icons/android/quickshop/icon-48-mdpi.png
res/icons/ios/quickshop/icon-72-hdpi.png
res/icons/ios/quickshop/icon-96-xhdpi.png
and I want to replace it to the following (quickshop is dynamic and can be any series of characters, mostly [az][AZ]) 并且我想将其替换为以下内容(quickshop是动态的,可以是任何一系列字符,主要是[az] [AZ])
res/icons/android/homecenter/icon-36-ldpi.png
res/icons/android/homecenter/icon-48-mdpi.png
res/icons/ios/homecenter/icon-72-hdpi.png
res/icons/ios/homecenter/icon-96-xhdpi.png
I was always very lousy when it comes to regular expressions, anyone could help? 对于正则表达式,我总是很烂,有人可以帮忙吗?
Try this: 尝试这个:
/(([\w]+\/){3})([^\/]+)(\/.+)/gm
var re = /(([\w]+\/){3})([^\/]+)(\/.+)/gm;
var str = 'res/icons/android/quickshop/icon-36-ldpi.png';
var replaceWord = 'homecenter'
var subst = '$1' + replaceWord + '$4';
var result = str.replace(re, subst);
// show result
window.alert(result);
could even be written as a function: 甚至可以写成一个函数:
function replaceURL(url, strReplace){ let re = /(([\\w]+\\/){3})([^\\/]+)(\\/.+)/gm; var subst = '$1' + strReplace + '$4'; return url.replace(re, subst); } var originalURL = 'res/icons/android/quickshop/icon-36-ldpi.png'; var replaceWord = 'homepage'; var newURL = replaceURL(originalURL, replaceWord); document.write(newURL);
Try this: 尝试这个:
var str = "res/icons/android/quickshop/icon-36-ldpi.png\\nres/icons/android/quickshop/icon-48-mdpi.png\\nres/icons/ios/quickshop/icon-72-hdpi.png\\nres/icons/ios/quickshop/icon-96-xhdpi.png", result = str.replace(/([\\w.-]+)(\\/[\\w.-]+)$/gm,"homecenter$2"); console.log(result); alert(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.