我可以通過使用 split 方法和 pop 方法(例如
.split("/").pop().
但通常,在 URL 的末尾有一個斜杠,如下所示:https ://exmaple.com/123/456/
它將回傳空,因為在最后一個斜杠之后沒有任何內容。
如何以最簡單的方式獲得 URL 最后一部分中的數字“6”?
uj5u.com熱心網友回復:
一種選擇是只洗掉斜杠,并回傳最后一個字符,無論它是什么。
這是一個簡單的例子:
const getLastChar = (str) =>
str.replaceAll('/', '').slice(-1);
// Example #1 - Trailing slash
console.log(getLastChar('https://exmaple.com/123/456/'));
// Example #2 - No trailing slash
console.log(getLastChar('https://exmaple.com/123/456'));
如果它基于用戶輸入,請不要忘記檢查字串是否存在/已定義:)
uj5u.com熱心網友回復:
只需洗掉最后一個“/”就像這樣:
let str = "https://example.com/abc/123/";
//if the str has a "/" at the end, remove it
if (str.endsWith("/")) {
str = str.slice(0, -1);
}
// str = "https://example.com/abc/123"
console.log(str);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/475257.html
標籤:javascript
