简体   繁体   中英

Javascript/jQuery string manipulation?

I'm trying to either grab only part of this URL or inject part of a string into it (whichever is simplest).

Here's the URL:

http://www.goodbuytimeshare.com/listings/min:1000/max:150000/agreements:rent,buy/properties:apartment,condo,hotel,resort/show:4/

I figure I either need to be able to tim it down to:

/listings/min:1000/max:150000/agreements:rent,buy/properties:apartment,condo,hotel,resort/

Or turn it into:

http://www.goodbuytimeshare.com/listings/ajax/min:1000/max:150000/agreements:rent,buy/properties:apartment,condo,hotel,resort/show:4/start:1/end:100/

(Same URL but "ajax/" would be added after the ".com/")

Which of these would be simpler?

Simple, use regex!

var myString = "http://www.goodbuytimeshare.com/listings/min:1000/max:150000/agreements:rent,buy/properties:apartment,condo,hotel,resort/show:4/";
var matches = (/^http:\/\/[a-zA-Z0-9\.]+(\/.+)$/).exec(myString);
var mySubString = matches[1];

Although, now you have two problems . ;-)

Here is non-regex solution. Of course regex is succinct.

var original = "http://www.goodbuytimeshare.com/listings/min:1000/max:150000/agreements:rent,buy/properties:apartment,condo,hotel,resort/show:4/";

// split into an array of separate fields

var fields = original.split("/")

var results = "";

for (i=0;i < fields.length;i++) {
// Insert ajax/ in the fourth position

if (i == 3) {
   results += "ajax/";
}

results += fields[i] 

// don't put the slash on the last item

if (i < (fields.length -1)) {
   results += "/";
}
}

// write out the results and append more

document.write(results + "start:1/end:100/");

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