Merita Ademi Merita Ademi - 1 month ago 5
Javascript Question

Remove all characters of a string after the fourth slash"/"

I'm looking for a way to remove the fourth slash(/), (and everything following it) from a string ,this function to be for every line list from "input text area"

Example: if i have a list "Vertically" in Input text area(days of the week)

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


when i click button remove ,results in Output Textarea to be "Vertically" like this:

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


my code:

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("");

}


thank you for your help.

Answer

You can use Array#split, Array#map, Array#join and Array#slice methods and do something like this.

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')
)


Or with String#replace method.

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')
)

Comments