简体   繁体   中英

Find value in String and delete it an everything else after it

If I have a string which could be either

index.php?value1=123&value2=xyz

or

index.php?value2=xyz

how would I remove &value2=xyz or ?value2=xyz if value2 exists in the string?

xyz will be random each time whereas the name value2 will rename constant but the length of xyz will always be the same

Perhaps the simplest approach is:

var valueToKeep = value.split(/[&?]value2/)[0];

Note that this will remove everything after the &value2 or ?value2 part. As an alternative, I would propose the following, which will remove the value2=... part, even if it occurs mid-url:

var valueToKeep = value.replace(/value2[^&]*&?/, "");

http://jsfiddle.net/LTH7j/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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