【问题标题】:Javascript string replace certain charactersJavascript字符串替换某些字符
【发布时间】:2018-08-23 09:58:31
【问题描述】:

我有这个字符串:

var s = '/channels/mtb/videos?page=2&per_page=100&fields=uri%2Cname%2Cdescription%2Cduration%2Cwidth%2Cheight%2Cprivacy%2Cpictures.sizes&sort=date&direction=asc&filter=embeddable&filter_embeddable=true'

我想替换 per_page 编号(在本例中为 100,但它可以是 1-100 之间的任何数字,也许更多?)

我可以选择字符串的第一部分:

var s1 = s.substr(0, s.lastIndexOf('per_page=')+9)

给我:

/channels/mtb/videos?page=2&per_page=

但是在那之后我将如何选择下一个“&”以便替换出现的数字?

不要假设相同的参数顺序!

【问题讨论】:

  • 我建议使用正则表达式而不是 lastIndexOf 和 substr 进行这种替换。
  • substr 的第一个参数是开始搜索的起始索引,因此您可以从第一次搜索的末尾开始,然后查找下一个 &

标签: javascript string replace


【解决方案1】:

使用带有正则表达式的replace 来查找文本per_page= 之后的数字。像这样:

s.replace(/per_page=\d+/,"per_page=" + 33)

用你想要的号码替换33

结果:

"/channels/mtb/videos?page=2&per_page=33&fields=uri%2Cname%2Cdescription%2Cduration%2Cwidth%2Cheight%2Cprivacy%2Cpictures.sizes&sort=date&direction=asc&filter=embeddable&filter_embeddable=true"

【讨论】:

  • [?&]per_page= 会更好地匹配密钥
【解决方案2】:

您可以使用以下正则表达式替换您想要的内容。

正则表达式:- /per_page=[\d]*/g(这只是您的要求)

var new_no=12;  //change 100 to 12
var x='/channels/mtb/videos?page=2&per_page=100&fields=uri%2Cname%2Cdescription%2Cduration%2Cwidth%2Cheight%2Cprivacy%2Cpictures.sizes&sort=date&direction=asc&filter=embeddable&filter_embeddable=true';

var y=x.replace(/per_page=[\d]*/g,'per_page='+new_no);
console.log(y);

解释:-

/per_page=[\d]*/g

/          ----> is for regex pattern(it inform that from next character onward whatever it encounter will be regex pattern)
per_page=  ----> try to find 'per_page=' in string 
[\d]*      ----> match 0 or more digit (it match until non digit encounter)
/g         ---->/ to indicate end of regex pattern and 'g' is for global means find in all string(not only first occurrence) 

【讨论】:

    【解决方案3】:
    var matches = /(.*\bper_page=)(\d+)(.*)/;
    
    if (matches) {
      s = matches[0] + newValue + matches[2];
    }
    

    【讨论】:

    • 我什至不确定这个提交是否回答了原始问题。即使是这样,我也建议提供一些评论。
    • 虽然这似乎回答了这个问题,但提供一些解释将提高答案的价值。请尽量避免仅使用代码的答案。最好的问候
    【解决方案4】:

    使用Array.filter,您可以这样做,将文本拆分为键/值对,并过滤掉以per_page= 开头的文本。

    堆栈sn-p

    var s = '/channels/mtb/videos?page=2&per_page=100&fields=uri%2Cname%2Cdescription%2Cduration%2Cwidth%2Cheight%2Cprivacy%2Cpictures.sizes&sort=date&direction=asc&filter=embeddable&filter_embeddable=true'
    
    var kv_pairs = s.split('&');
    var s2 = s.replace((kv_pairs.filter(w => w.startsWith('per_page=')))[0],'per_page=' + 123);
    
    //console.log(s2);

    【讨论】:

      【解决方案5】:

      从 lastIndexOf-per_page 的索引开始,而不是 0。 获取第一个 & 的索引并创建一个 substr s2 到最后。 然后连接 s1 + nr + s2。 我不会使用正则表达式,因为这个简单的东西要慢得多。

      【讨论】:

        猜你喜欢
        • 2023-03-04
        • 2012-02-17
        • 2013-07-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-30
        • 2011-02-21
        • 2014-12-13
        相关资源
        最近更新 更多