【问题标题】:Regex to replace only some / characters inside strings正则表达式仅替换字符串中的一些 / 字符
【发布时间】:2021-02-03 11:35:23
【问题描述】:

如何使用替换方法获取正则表达式?就我而言,我有一个使用 char / between的字符串。

输入:

var string = "cn/" + companyName + "/st/" + state + "/ic/" + incCi + "/pr/" + priority + "/es/" + emplSystem + "/mc/" + mainCategory + "/sc/" + subCategory + "/ty/" + type;

输出:

"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

【问题讨论】:

  • 你看过如何在 JS 中对 URL 进行编码吗?
  • 您需要替换源字符串mainCategorysubCategory,而不是最终字符串。

标签: javascript regex


【解决方案1】:

您可以使用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)

【讨论】:

    【解决方案2】:

    在我看来,您正在寻找对 url 进行编码。可以在JS中使用encodeURI对url进行编码。

    let encodedURL = encodeURI(url);
    

    您可以阅读更多关于它的信息here

    如果您想完全编码字符串而不忽略任何与域相关的部分,您可以encodeURIComponent()

    let encodedURL = encodeURIComponent(url);
    

    您可以阅读更多关于它们的区别here

    编辑:

    如果您没有对 url 进行编码,并且只想在 mainCategorysubCategory 中将 / 替换为 %2F,那么您需要在加入它们之前对字符串本身运行正则表达式。

    var string = "cn/" + companyName + 
        "/st/" + state + 
        "/ic/" + incCi + 
        "/pr/" + priority + 
        "/es/" + emplSystem + 
        "/mc/" + mainCategory.replace("\/", "%2F")  +
         "/sc/" + subCategory.replace("\/", "%2F")  + 
        "/ty/" + type;
    

    【讨论】:

    • @mplungjan 但这将对所有字符进行编码,我认为 OP 只想更改 '/'。
    • 当然,如果有其他特殊字符,但如果没有,编码也可以工作
    猜你喜欢
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 2012-04-26
    • 2013-01-21
    • 2018-07-13
    • 2017-02-04
    相关资源
    最近更新 更多