【问题标题】:Javascript/jQuery string manipulation?Javascript/jQuery 字符串操作?
【发布时间】:2009-06-21 01:08:41
【问题描述】:

我正在尝试仅获取此 URL 的一部分或将部分字符串注入其中(以最简单的为准)。

这是网址:

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

我想我要么需要能够将其计时到:

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

或者把它变成:

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

(相同的网址,但“.com/”后会添加“ajax/”)

哪些会更简单?

【问题讨论】:

    标签: javascript jquery url string


    【解决方案1】:

    简单,使用正则表达式!

    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];
    

    虽然,now you have two problems。 ;-)

    【讨论】:

      【解决方案2】:

      这是非正则表达式解决方案。当然,正则表达式很简洁。

      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/");
      

      【讨论】:

        猜你喜欢
        • 2021-08-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-26
        • 2019-04-16
        • 2022-08-03
        相关资源
        最近更新 更多