【问题标题】:How do I change the delimiter from comma to pipe in the following JS?如何在以下 JS 中将分隔符从逗号更改为管道?
【发布时间】:2014-06-11 19:08:19
【问题描述】:

以下JS函数输出的分隔符​​是值之间的逗号。如何将其更改为管道:'|' ?

function siteHier(){

    // Grab Path
    var myUrlOriginal = window.location.pathname;

    // Remove everything after first '.'
    var oPath = myUrlOriginal.substr(0, myUrlOriginal.lastIndexOf("."));
    //console.log(oPath);

    // Split data into sections
    var nPath = oPath.split('/');
    //console.log('Hier: ' + nPath);

    // Replace ',' with '|'
    var stringReplaceFrom = /,/g;
    var stringReplaceTo = '|';
    var dPath = nPath.join(',').replace(stringReplaceFrom,stringReplaceTo).split();
    //var dPath = nPath;
    console.log(dPath);

    // Final Value
    var hPath = 'homepage' + dPath;
    //console.log(hPath);

    return hPath;
}

【问题讨论】:

  • 看来分隔符(当您调用split 时)是一个正斜杠。逗号在哪里?
  • 默认添加逗号 Elliott。 .split() 所做的是将“/”处的段分开。我说的是把所有东西放在一起时的输出。

标签: javascript


【解决方案1】:

如果你想用javascript替换一些东西,你可以使用.replace()方法。

此方法的第一个参数可以是您要查找的正则表达式。第二个是您要替换的字符串。

您只需要一个简单的 Replace 就可以使用这种示例:

var string = 'some,string';
string.replace(/,/g , '|'); //output: some|string

但要小心!它将取代每次出现的标志!

【讨论】:

  • 今天晚些时候我会试试这个;但是,您的解决方案乍一看肯定会奏效。谢谢纳米。
  • 我添加了你的解决方案,但它给出了一个错误:Uncaught TypeError: undefined is not a function。
  • 我用最新的代码更新了 OP,给出了 Uncaught TypeError。
  • 替换功能不适用于数组(您的拆分返回的内容)。在拆分之前进行替换
  • 我最终做的是:var stringReplaceFrom = /,/g;var stringReplaceTo = '|';var dPath = nPath.join(',').replace(stringReplaceFrom,stringReplaceTo).split();
猜你喜欢
  • 2022-11-17
  • 2019-05-21
  • 2020-02-02
  • 1970-01-01
  • 1970-01-01
  • 2016-09-05
  • 1970-01-01
  • 2021-07-28
  • 1970-01-01
相关资源
最近更新 更多