本文介绍了用正负负替换Javascript RegExp的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用JS替换当前页面的查询字符串中的某些值.例如:从category=Old Valuecategory=New Value.编写代码如下:

I am trying to replace some value in the query string of the current page using JS. Eg: from category=Old Value to category=New Value.To code looks like this:

var sNewValue = 'New Value';
sQueryString = sQueryString.replace(/category=[^&]+&?/, 'category=' + sNewValue);

除了带有&"号的值外,它都可以正常工作.幸运的是,所有&"号都是URL编码的,因此我知道应该在& 之前丢弃& .我想我应该先行使用,但我不知道该怎么做.我尝试了此正则表达式,但没有运气:/category=[^&(?!amp;)]+&?/

It works fine except for values that have ampersands. Luckily all the ampersands are URL encoded, so I know I should discard the amp; before the &. I think I should use lookaheads, but I don't know how. I tried this regular expression, but with no luck: /category=[^&(?!amp;)]+&?/

谢谢

推荐答案

为什么将&符号编码为& amp;而不是%26?还是我读错了您的问题?

Why are ampersands being encoded as & instead of %26? Or am I reading your question wrong?

如果这是需要的方式,那么如果首先将其分成名称/值对,则处理该查询字符串可能会更容易.

If that's the way it needs to be, it might be easier for you to deal with this query string if you break it into name/value pairs first.

var pairStrings = sQueryString.split(/&(?!amp;)/gi);

然后,您可以使用每个值,而不必担心它是否包含已编码的&是否.

Then you can work with each value without worrying if it contains an encoded & or not.

这篇关于用正负负替换Javascript RegExp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 20:18