简体   繁体   English

如何使用javascript在URL地址中找到字符串的一部分?

[英]How can i find part of the string in url address with javascript?

Good evening, I have a problem to find string from url address when I click on next page, for example I have url: http://www.example.cz/example/example-example/page/2/ <- hyphen is optinal. 晚上好,当我单击下一页时,从URL地址查找字符串时遇到问题,例如,我的URL为: http : //www.example.cz/example/example-example/page/2/ <-连字符为optinal。 I need to find part http://www.example.cz/example/example-example/ <- without part page/number/ and save it to variable. 我需要找到部分http://www.example.cz/example/example-example/ <-没有部分页面/编号/并将其保存到变量中。 Can you guys help me how to do it ? 你们能帮我怎么做吗?

You could split on / and then reform the string. 您可以分割/ ,然后重新格式化字符串。

For example (this assumes http:// is part of the string): 例如(假设http://是字符串的一部分):

"http://www.example.cz/example/example-example/page/2/".split("/").slice(0,5).join("/")
  1. Split on / 分割为/
  2. Slice out the first 5 items in the array. 切出数组中的前5个项目。
  3. Re-join them together with a / /将他们重新加入

Results: "http://www.example.cz/example/example-example" 结果: "http://www.example.cz/example/example-example"

If page is always in the url and also what needs to be removed, you can simply split on 'page' and take the first element of the resulting array. 如果page始终在url中,并且还有需要删除的内容,则可以简单地在'page'上拆分并获取结果数组的第一个元素。

var url = "http://www.example.cz/example/example-example/page/2/",
    urlParsed = url.split("page")[0];

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

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