[英]Regex to replace only some / characters inside strings
如何使用替换方法获取正则表达式? 就我而言,我有一个使用 char / 之间的字符串。
输入:
var string = "cn/" + companyName + "/st/" + state + "/ic/" + incCi + "/pr/" + priority + "/es/" + emplSystem + "/mc/" + mainCategory + "/sc/" + subCategory + "/ty/" + type;
output:
"cn/Nemesis Group/st/2/ic/null/pr/1 - High/es/null/mc/Add/Button/sc/Core/Label/ty/str"
变量 mainCategory 和 subCategory 返回字符串 'Add/Button' 和 'Core/Label'
如何在不更改任何其他字符的情况下将 'Add/Button' 替换为 'Add%2FButton' 和 'Core/Label' 到 'Core%2FLabel'?
string.replace("\/", "%2F")
将所有字符 / 更改为 %2F
您可以使用encodeURIComponent()
和decodeURIComponent()
来转换这个字符串
例子:
const companyName = "Company", state = "State", incCi = "IncCi", priority = "Priority", emplSystem = "EmplSystem", mainCategory = 'Add/Button', subCategory = 'Core/Label', type = "Type"; var string = "cn/" + companyName + "/st/" + state + "/ic/" + incCi + "/pr/" + priority + "/es/" + emplSystem + "/mc/" + encodeURIComponent(mainCategory) + "/sc/" + encodeURIComponent(subCategory) + "/ty/" + type; console.log(string)
在我看来,您正在寻找编码 url。 您可以在 JS 中使用encodeURI
来编码 url。
let encodedURL = encodeURI(url);
你可以在这里阅读更多关于它的信息。
如果您想完全编码字符串而不忽略任何与域相关的部分,您可以使用encodeURIComponent()
let encodedURL = encodeURIComponent(url);
你可以在这里阅读更多关于它们的区别。
编辑:
如果您没有编码 url 并且您只想在mainCategory
和subCategory
中用%2F
替换/
,那么您需要在加入它们之前在字符串本身上运行正则表达式。
var string = "cn/" + companyName +
"/st/" + state +
"/ic/" + incCi +
"/pr/" + priority +
"/es/" + emplSystem +
"/mc/" + mainCategory.replace("\/", "%2F") +
"/sc/" + subCategory.replace("\/", "%2F") +
"/ty/" + type;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.