我有这个字符串:
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=
但是我如何选择之后的下一个“&”以便替换数字出现?
不要假设参数的顺序相同!
最佳答案
您可以使用以下正则表达式来替换您想要的内容。
正则表达式:- /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)
关于Javascript字符串替换某些字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49285079/