我有一個格式的網址 url = /api/v1/customers/123/spend/456
我需要將斜杠之間的數字替換為*.Same 以將 url 末尾的數字替換為*.
所以我預期的 url 輸出 url = /api/v1/customers/*/spend/*
我們如何使用 RegEx 實作這一目標?
uj5u.com熱心網友回復:
您可以使用正則運算式替換:
var url = "url = /api/v1/customers/123/spend/456";
var output = url.replace(/\/\d (\/|$)/g, "/*$1");
console.log(output);
此處使用的正則運算式模式匹配:
/ / separator
\d a number
(/|$) either / or the end of the URL (capture)
請注意,我們替換為/*$1,其中$1可能是也可能不是捕獲的分隔符(不是在最終數字的情況下)。
uj5u.com熱心網友回復:
您可以使用環視(lookahead & lookbehind)來做到這一點,使用這些您只能匹配數字。
let pattern = /(?<=\/)\d (?=\/|$)/g
let url = "/api/v1/customers/123/spend/456"
url = url.replace(pattern, '*')
console.log(url)
(?<=\/)\d (?=\/|$)
(?<=\/) lookbehind which matches the / before a number
\d matches one of more digits
(?=\/|$) loohahead which matches either the / after the number or the end of the string
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/437195.html
標籤:javascript 节点.js 正则表达式 细绳 网址
上一篇:如何撰寫Lua模式將字串(嵌套陣列)轉換為真實陣列?
下一篇:來自復雜子查詢的Hive子字串
