【问题标题】:How do I replace all the / in a URL with ,?如何将 URL 中的所有 / 替换为 ,?
【发布时间】:2020-12-16 06:57:56
【问题描述】:

我正在尝试将 URL 输入转换为适合我的 api 的格式,但遇到了问题。 每当我使用(/blue/g, "red"); 执行全局搜索和替换时,它都可以正常工作。

但每当我尝试做同样的操作,但使用斜线 ((///g, "red");) 时,它会给我一个 语法错误。

有没有办法解决这个问题?

【问题讨论】:

  • 尝试正则表达式来替换它 - srt.replace(/\//g, ',')
  • 你能在问题中添加一个最小的例子和错误吗?
  • 对不起,我试过了,效果很好
  • 也许 replaceAll() 更适合这里?
  • @Alex 但是 OP 的代码也可以。您是否收到 OP 代码的语法错误?

标签: javascript frontend web-frontend


【解决方案1】:
var strings = "yellow/red/blue";
console.log(strings);
strings = strings.replace(/\//g,",");
console.log(strings);

这应该可行。

【讨论】:

    【解决方案2】:

    您正在 URL 中搜索 replace / by ,

    解决方法如下:

    const windowURL= 'https://stackoverflow.com/questions/65318599/how-do-i-replace-all-the-in-a-url-with';
    const URL = new URL(windowURL);
    const path = URL.pathname.replaceAll('/', ',')
    
    console.log('Updated path in which `/` is replaced by `,` =>>', path)
    

    【讨论】:

      猜你喜欢
      • 2013-01-29
      • 2020-11-12
      • 2018-07-27
      • 1970-01-01
      • 1970-01-01
      • 2018-06-28
      • 1970-01-01
      • 2019-01-04
      • 2019-06-17
      相关资源
      最近更新 更多