var value = "ID=advIcon1&CLASS=advIcon&PAGE=43&TOP=2%&LEFT=15%&WIDTH=20%&HEIGHT=10%&RSC=http://www.canon.com.hk/40th/index.html?source=seriesbanner&ICON=http://203.80.1.28/FlippingBook/Dev/Frontend/source/adv/tc_bn_314.jpg&ALT=Cannon Adv"
我想要实现的是
&RSC=http://www.canon.com.hk/40th/index.html?source=seriesbanner
到
&RSC=http://www.canon.com.hk/40th/index.html?source#seriesbanner
替换&RSC
和&ICON
value = value.replace (/&RSC=%[=]+%&ICON/,/&RSC=%[#]+%&ICON/);
以上是我试过的代码,虽然没有工作,如何解决问题?谢谢
答案 0 :(得分:2)
我会这样做:
var value = "ID=advIcon1&CLASS=advIcon&PAGE=43&TO...";
var startIndex = value.indexOf("&RSC");
var endIndex = value.indexOf("&ICON");
var head = value.substring(0, startIndex);
var tail = value.substring(endIndex);
var body = value.substring(startIndex, endIndex);
var result = head + body.replace(/=/g, '#') + tail;
我没有看到用一个疯狂的正则表达式做整件事的任何优势。
这只会让您的代码难以阅读且效率降低。
更好的是,让它成为一个可以重复使用的功能:
// Replaces every occurrence of replaceThis with withThis in input between
// startPattern and endPattern.
function replaceCharactersBetween(input, startPattern, endPattern, replaceThis, withThis) {
var startIndex = input.indexOf("startPattern");
var endIndex = input.indexOf("endPattern");
var head = input.substring(0, startIndex);
var tail = input.substring(endIndex);
var body = input.substring(startIndex, endIndex);
var regex = new RegExp(replaceThis, 'g');
return head + body.replace(regex, withThis) + tail;
}
答案 1 :(得分:0)
尝试:
value = value.replace(/RSC=([^=]+)=([^=]+)/, 'RSC=$1#$2');
您也应该查看endoceURIComponent()
。