用javascript替换掉一部分字符串

时间:2018-11-20 07:15:42

标签: javascript ecmascript-6

我有这个字符串,如何制作到.html呢?

字符串

https://www.lazada.com.ph/products/fujitsu-standard-aa-rechargeable-battery-2000mah-4pcs-i237968048-s311807989.html?spm=a2o4k.searchlist.list.47.7f1a484d4gpCFd&search=1

放入

https://www.lazada.com.ph/products/fujitsu-standard-aa-rechargeable-battery-2000mah-4pcs-i237968048-s311807989.html

4 个答案:

答案 0 :(得分:3)

也许您正在寻找类似以下示例的内容:

var str = 'https://www.lazada.com.ph/products/fujitsu-standard-aa-rechargeable-battery-2000mah-4pcs-i237968048-s311807989.html?spm=a2o4k.searchlist.list.47.7f1a484d4gpCFd&search=1';

console.log(str.match('^.+\.html')[0]);

我已将正则表达式与模式^.+\.html配合使用以匹配网址。正规表达式表示:从字符串的开头到.html


如果要将网址分为两部分,可以尝试:

var str = 'https://www.lazada.com.ph/products/fujitsu-standard-aa-rechargeable-battery-2000mah-4pcs-i237968048-s311807989.html?spm=a2o4k.searchlist.list.47.7f1a484d4gpCFd&search=1';

var parts = str.split(/\?/);

console.log(parts[0]);
console.log('?' + parts[1]);

答案 1 :(得分:1)

您可以使用String.prototype.split()

var url =  "https://www.lazada.com.ph/products/fujitsu-standard-aa-rechargeable-battery-2000mah-4pcs-i237968048-s311807989.html?spm=a2o4k.searchlist.list.47.7f1a484d4gpCFd&search=1";


console.log(url.split('?', 1)[0])

答案 2 :(得分:0)

您可以使用URL API

root@ip-10-17-0-114:~# cat /etc/hostname
ip-10-17-0-15
root@ip-10-17-0-114:~# hostname
ip-10-17-0-114

答案 3 :(得分:0)

这可以根据您的要求正常工作

let url = "https://www.lazada.com.ph/products/fujitsu-standard-aa-rechargeable- 
         battery-2000mah-4pcs-i237968048-s311807989.html?spm=a2o4k.searchlist.list.47.7f1a484d4gpCFd&search=1"


url.substring(0, <nbsp> url.indexOf('.html')<nbsp> + <nbsp>5)