Javascript字符串替换某些字符

时间:2018-03-14 18:19:27

标签: javascript string replace

我有这个字符串:

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=

但我如何选择下一个'&'之后我可以替换号码出现吗?

不要假设参数顺序相同!

5 个答案:

答案 0 :(得分:3)

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

正则表达式: - /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) 

答案 1 :(得分:2)

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"

答案 2 :(得分:1)

使用Array.filter,您可以执行此操作,其中将文本拆分为键/值对,并过滤掉以per_page=开头的文本。

Stack snippet



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




答案 3 :(得分:1)

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

答案 4 :(得分:0)

var matches = /(.*\bper_page=)(\d+)(.*)/;

if (matches) {
  s = matches[0] + newValue + matches[2];
}
相关问题