Reputation: 53
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.
Upvotes: 2
Views: 207
Reputation: 115222
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')
)
Upvotes: 3
Reputation: 311308
The easiest would be to just split the string according to the /
and limit the number of returned elements to four, and the rejoin them:
function firstFourFields(s) {
return s.split('/', 4).join('/');
}
Upvotes: 6