[英]how to get particular string from url in javascript?
示例: https : //www.google.com/upload/images/2021-5-3/3fde799e-1b53-33aa-b6b4-181d00a26a1f/output-001.svg
我只想獲得“上傳/圖片”
通過使用 URL 類,您可以獲得路徑名。
let url = new URL("https://www.google.com/upload/images/2021-5-3/3fde799e-1b53-33aa-b6b4-181d00a26a1f/output-001.svg");
$ url.pathname -> "/upload/images/2021-5-3/3fde799e-1b53-33aa-b6b4-181d00a26a1f/output-001.svg"
let url = window.location.href;
let pathname = url.split('.com/')[1]
let param = pathname.split('/');
let result = `${param[0]}/${param[1]}`
這有點冗長,但可以為您提供所需的結果。
您可以使用正則表達式來匹配第 3 個和第 5 個斜杠之間的所有內容,例如:
let url = "https://www.google.com/upload/images/2021-5-3/3fde799e-1b53-33aa-b6b4-181d00a26a1f/output-001.svg";
let result = url.replace(/[^/]*\/[^/]*\/[^/]*\/([^/]*\/[^/]*).*/, "$1");
這導致
"upload/images"
這是獲取路由的簡單方法(不帶域的 URL):
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
template: 'Play with the routes'
})
export class MyComponent {
constructor(private router: Router) {}
ngOnInit() {
console.log(this.router.url);
}
}
從這一點開始,很容易使用路線並獲得您想要的部分:例如,當您找到/
時拆分字符串並僅連接您想要的部分。
您還可以考慮使用UrlSegment
(此處為文檔)。
您也可以在此處查看其他問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.