简体   繁体   English

如何使用javascript在以下情况下编写正则表达式?

[英]How to write regular expression in the following case using javascript?

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"

What I would like to achieve is from 我想要实现的是

&RSC=http://www.canon.com.hk/40th/index.html?source=seriesbanner

to

&RSC=http://www.canon.com.hk/40th/index.html?source#seriesbanner

which replace all the "=" between &RSC and &ICON 它取代了&RSC&ICON之间的所有“=”

value = value.replace (/&RSC=%[=]+%&ICON/,/&RSC=%[#]+%&ICON/); 

The above is the code I tried, not working though, how to fix the problem ? 以上是我试过的代码,虽然没有工作,如何解决问题? thanks 谢谢

I would do it like this: 我会这样做:

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;

I don't see any advantage in trying to do the whole thing with one crazy regex. 我没有看到用一个疯狂的正则表达式做整件事的任何优势。

That will only make your code harder to read and less efficient. 这只会使你的代码更难阅读,效率更低。

Better yet, make it a function you can re-use: 更好的是,让它成为一个可以重复使用的功能:

// 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;
}

Try: 尝试:

value = value.replace(/RSC=([^=]+)=([^=]+)/, 'RSC=$1#$2');

You should look at endoceURIComponent() as well. 您还应该查看endoceURIComponent()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM