代码之家  ›  专栏  ›  技术社区  ›  Morton

如何删除特定的多个字符串,然后保留另一个?

  •  1
  • Morton  · 技术社区  · 5 年前
    let result = 'Apple%00Juice%02';
    
    const removeOne = result.slice(5, 8); // get %00
    
    const removeTwo = result.slice(13, 16); // get %02
    

    slice 获取我想要移除的部分,而不是我想要获取的部分。

    是不是任何函数都可以让我得到 result 变成“苹果汁”?

    3 回复  |  直到 5 年前
        1
  •  3
  •   Yousaf    5 年前

    使用正则表达式匹配要从字符串中删除的部分,然后使用 replace()

    const str = "Apple%00Juice%02";
    const regex = /%\d+/g;
    
    const result = str.replace(regex, " ").trim()
    
    console.log(result);

    • % -匹配角色 字面上
    • \d+ -匹配任意数字 0 到 9
    • %\d+ %
        2
  •  2
  •   Aditya    5 年前

    您可以通过使用 .replace() 功能

    let result = 'Apple%00Juice%02';
    result = result.replace('%00', ' ');
    result = result.replace('%02', '');
    console.log(result);

    阅读更多关于 .替换() 作用于 MDN Docs

    缩小 @Yousaf 我的回答

    let result = "Apple%00Juice%02";
    result = result.replace(/%\d+/g, " ").trim()
    
    console.log(result);
        3
  •  0
  •   Tony Grätscher    5 年前

    可以使用replace(),但这不是一个可持续的解决方案。URL编码“%00”是ASCII字符。这表明该字符串已被编码为URL的错误字符格式。因此,您必须查看读取数据库或文件时使用的字符格式。例如UTF-8、ISO 8859-1

    以正确的字符格式编码时。您可以使用decodeURIComponent(str)方法在JavaScript中对其进行解码吗。 more on this