繁体   English   中英

JavaScript 字符串 .replace 为 URL

[英]JavaScript string .replace for URL

我使用 chrome 扩展为数据库抓取站点,需要 JavaScript 清理功能的帮助

例如

https://www.alibaba.com/product-detail/_60789694386.html?spm=a2700.galleryofferlist.normalList.1.5be41470uWBNGm&s=p

我的目标输出是:

_60789694386.html

.html 之后的所有内容都需要删除,但由于每个 URL 中的内容不同 - 我迷路了

输出在一个 .csv 文件中,我在其中运行 JavaScript 来清理数据。

   this.values[8] = this.values[8].replace("https://www.alibaba.com/product-detail/","");

this.values[8] 是我如何定位脚本中的列。 (第 8 列包含 URL)

好吧,您可以使用split

var final = this.values[8].split('.html')[0]

split为您提供由字符串拆分的项目数组,在您的情况下为'.html' ,然后您取第一个。

考虑使用substr

this.values[8] = this.values[8].substr(0,this.values[8].indexOf('?'))

您可以使用 split 方法将文本从 ? 如示例中所示。

 var link = "https://www.alibaba.com/product-detail/_60789694386.html?spm=a2700.galleryofferlist.normalList.1.5be41470uWBNGm&s=p" var result = link.split('?')[0].replace("https://www.alibaba.com/product-detail/",""); console.log(result);

不确定我理解你的问题,但试试这个

 var s = 'https://www.alibaba.com/product-detail/_60789694386.html?spm=a2700.galleryofferlist.normalList.1.5be41470uWBNGm&s=p' s = s.substring(0, s.indexOf('?')); console.log( s );

因为当你不关心可读性时......

this.values[8] = new URL(this.values[8]).pathname.split("/").pop().replace(".html","");

替代,不使用拆分

 var link = "https://www.alibaba.com/product-detail/_60789694386.html?spm=a2700.galleryofferlist.normalList.1.5be41470uWBNGm&s=p" var result = link.replace('https://www.alibaba.com/product-detail/', '').replace(/\\?.*$/, ''); console.log(result);

您可以使用正则表达式来完成它。 据我所知,您执行以下操作:

    var v = "https://www.alibaba.com/product-detail/_60789694386.html?spm=a2700.galleryofferlist.normalList.1.5be41470uWBNGm&s=p"
    result = (v.match(/[^\/]+$/)[0]);
    result = result.substring(0,result.indexOf('?'));
    console.log(result);    // will return _60789694386.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM