这是我的代码:
var str = 'http://localhost/myweb/login/resend_password?destination=http://localhost%2Fmyweb%2Fsearch%3Fs%3Dislamic_sources%26q%3D%25D8%25B3%25D9%2584%25D8%25A7%25D9%2585';
var res = str.replace('/(destination=)[^$|&]+/', '$1newval');
console.log(res);

虽然这是预期的结果:
http://localhost/myweb/login/resend_password?destination=newval
为什么替换在我的代码中不起作用?注意到它适用于this fiddle。
答案 0 :(得分:1)
您应该使用:
var str = 'http://localhost/myweb/login/resend_password?destination=http://localhost%2Fmyweb%2Fsearch%3Fs%3Dislamic_sources%26q%3D%25D8%25B3%25D9%2584%25D8%25A7%25D9%2585';
var res = str.replace(/(destination=)[^&]*/, '$1newval');
console.log(res);
正则表达式不应该在引号中,正则表达式需要一些修复,因为[^$|&]+
没有做你认为它正在做的事情。
[^$|&]+
匹配任何非$
而非|
而非&
而不只是非&
个字符。
答案 1 :(得分:0)
将reg表达式放在没有'像这样
var str = 'http://localhost/myweb/login/resend_password?destination=http://localhost%2Fmyweb%2Fsearch%3Fs%3Dislamic_sources%26q%3D%25D8%25B3%25D9%2584%25D8%25A7%25D9%2585';
var res = str.replace(/(destination=)[^$|&]+/, '$1newval');
console.log(res);

答案 2 :(得分:0)
以下解决方案有效 `
var str = 'http://localhost/myweb/login/resend_password?destination=http://localhost%2Fmyweb%2Fsearch%3Fs%3Dislamic_sources%26q%3D%25D8%25B3%25D9%2584%25D8%25A7%25D9%2585';
var regexpr= /(destination=)[^$|&]+/g;
var res = str.replace(regexpr, '$1newval');
console.log(res);
` 你必须删除引号!