简体   繁体   中英

javascript regular expression optional character

I want to replace url parameters by using regular expression.

My code :

query = window.location.search;
query.replace(new RegExp(query.match('f=(.*)&?')[1],'g'),'2');

But there is possible two situation,

first:

query can be "?f=23"

second:

query can be "?f=23&id=1",

my code work for first situation , but it doesn't work for second situation.

How can I replace my query for both situation ?


function control(parameter,value) {

var newUrl;
var url = window.location.href.split('?')[0];
var query = window.location.search;
var check = query.indexOf('f');

if (check == -1) {

    var qCheck = query.indexOf('?');
    if (qCheck == -1) {
        query = query+'?'+parameter+'='+value;
    } else {
        query = query+'&'+parameter+'='+value;
    }

} else {

    var c = query.indexOf('&');
    if(c == -1) {
        query = query.replace(new RegExp(query.match(parameter+'=(.*)')[1],'g'),value);

    } else {

        query = query.replace(new RegExp(query.match('f=(.*)&')[1],'g'),value);
    }

}   

    history.pushState(null,null,url+query); 
}

Try this one

/(f=)([^\s|&]+)/g

Usage in JavaScript

'?f=23'.replace(/(f=)([^\s|&]+)?/g, '$12');
'?f=23&id=1'.replace(/(f=)([^\s|&]+)?/g, '$12');
'?a=22&f=24'.replace(/(f=)([^\s|&]+)?/g, '$12');

Output:

?f=2
?f=2&id=1
?a=22&f=2

Demo

From what I understand, you want to replace the parameter f with the value 2, therefore:

query = window.location.search;
query = query.replace( /f=(.*?)&?/g, 'f=2' );

the .*? makes the match non-greedy.

Here is what you want:

query = window.location.search; // "?f=23&id=1"
query.replace( /(f=).*(&)/, '$1'+ '2' +'$2' );

> "?f=2&id=1"

query.replace( /(f=).*(&)/, '$1'+ 'something' +'$2' );

> "?f=something&id=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