删除第四个斜杠后的所有字符串" /"

时间:2016-10-14 18:50:25

标签: javascript regex string

我正在寻找一种方法来从字符串中删除第四个斜杠(/),以及它后面的所有内容,这个函数适用于来自"输入文本区域的每个行列表"

示例:如果我有一个列表"垂直"在输入文本区域(星期几)

Monday/February/8/2016/08:05:07/GMT-0700 (PDT)
Tuesday/February/9/2016/09:07:07/GMT-0700 (PDT)
Wednesday/February/10/2016/01:04:07/GMT-0700 (PDT)
Thursday/February/11/2016/05:15:07/GMT-0700 (PDT)
etc

当我点击按钮删除时,导致输出文本区域为"垂直"像这样:

Monday/February/8/2016
Tuesday/February/9/2016
Wednesday/February/10/2016
Thursday/February/11/2016

我的代码:

function remove_list() {
  var count = 0;
  var list = document.myForm.Input.value;
  list = list.replace(/^((?:[^ ]* ){3}[^ ]*) [/]*/gm, "$1");

  var listvalues = new Array();
  var newlist = new Array();

  listvalues = list.split(/[\s,]+/).join("");

  var hash = new Object();

  for (var i = 0; i < listvalues.length; i++) {
    if (hash[listvalues[i].toLowerCase()] != 0) {
      newlist = newlist.concat(listvalues[i]);
      hash[listvalues[i].toLowerCase()] = 1
    } else {
      count++;
    }
  }
  document.myForm.Output.value = newlist.join("");

}

谢谢你的帮助。

2 个答案:

答案 0 :(得分:6)

最简单的方法是根据/拆分字符串,并将返回的元素数限制为4,然后重新加入:

function firstFourFields(s) {
    return s.split('/', 4).join('/');
}

答案 1 :(得分:3)

您可以使用Array#splitArray#mapArray#joinArray#slice方法并执行此类操作。

&#13;
&#13;
var str = `Monday/February/8/2016/08:05:07/GMT-0700 (PDT)
Tuesday/February/9/2016/09:07:07/GMT-0700 (PDT)
Wednesday/February/10/2016/01:04:07/GMT-0700 (PDT)
Thursday/February/11/2016/05:15:07/GMT-0700 (PDT)`;

console.log(
  // split the string by newline
  str.split('\n')
  // iterate over array
  .map(function(v) {
    // generate the string where removed content after 4th /
    return v.split('/').slice(0, 3).join('/');
    // you can make it much more simpler as in @Mureinik answer
    // return v.split('/', 4).join('/');
    
    // re-join string elements
  }).join('\n')
)
&#13;
&#13;
&#13;

或使用String#replace方法。

&#13;
&#13;
var str = `Monday/February/8/2016/08:05:07/GMT-0700 (PDT)
Tuesday/February/9/2016/09:07:07/GMT-0700 (PDT)
Wednesday/February/10/2016/01:04:07/GMT-0700 (PDT)
Thursday/February/11/2016/05:15:07/GMT-0700 (PDT)`;

console.log(
  str.replace(/^((?:[^\/]*\/){3}[^\/]*)\/.+$/mg, '$1')
)
&#13;
&#13;
&#13;