简体   繁体   中英

Join and replace on multiple occurences of string

I have this string :

var data = "res_per_page=10&page_num=1&location_id=107&location_id=174&location_id=110&location_id=180"

I'd like to group all 'location_id' parameters into one, separated by _ . How to achieve that ? The result string should be as follows :

var data = "res_per_page=10&page_num=1&location_id=107_174_110_180"

How about; (assumes id's are numeric from 1 to 9 digits)

var newdata = [];
data = data.replace(/&?location_id=(\d{1,9})/ig, function(m, k, v) {
        newdata.push(k);
        return "";
    });
data += "&location_id=" + newdata.join("_");
alert(data);


in:  "res_per_page=10&page_num=1&location_id=107&location_id=174&location_id=110&location_id=180"
out: "res_per_page=10&page_num=1&location_id=107_174_110_180"

Here you go:

var dataInit = "res_per_page=10&page_num=1&location_id=107&"+
               "location_id=174&location_id=110&location_id=180"
               .split('&location_id='),
data = dataInit[0]+'&location_id='+dataInit.slice(1).join('_');

Now data 's value is: res_per_page=10&page_num=1&location_id=107_174_110_180

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