can i give more than one parameter to the split function in javascript to remove more than one thing and put it into array? for expamle:
var str= "This is Javascript String Split Function example ";
var wordArray=str.split(" ");
this will give me each word separately
in addition of this result, i want to remove "is" and "this" from the array, so can i put in the split function many parameter to remove from the beginning " " & "is" & "this" ? or should i use another function than split() ?
3 Answers 3
there are many ways to achieve what you want. Basically you want to remove is and this
so either you can do this:
a. If words you want to remove are always the first and the second one then
var filteredArray = str.split(" ").splice(2);
b. If words you want to remove can be anywhere in the string
var filteredArray = str.replace(/this|is/g, function(w){
switch(w){
case 'this':
return '' ;
case 'is':
return '';
}
}).trim().split(' ');
c. There is one more lame way to do this.
var str= "This is Javascript String Split Function example ";
var parts = str.split(' ');
var clean = [];
for (var i = 0; i < parts.length; i++) {
var part = parts[i];
if (part !== "This" && part !=="is")
clean.push(part);
}
d. using simple regex to replace multiple words
var str= "This is Javascript String Split Function example ";
var words = ['This', 'is'];
var text = str.replace(new RegExp('(' + words.join('|') + ')', 'g'), '').split(' ');
based on your need you can go for any one of them.
2 Comments
String.split takes two arguments, a separator and a limit. So basically you can remove entries from the end of the resulting array (limit the array), but not from the beginning.
Read more here: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/split
However, you can chain the resulting array with other array prototypes, so you can easily add a Array.splice to do what you want:
var wordArray = str.split(" ").splice(2);
If you want to specifically remove certain words, use Array.filter:
var wordArray = str.split(' ').filter(function(word) {
return !/(is|this)/i.test(word);
});
1 Comment
I wouldn't try to use split to remove things from a string. You should use "replace" to remove them, then split after.
var wordArray = str.replace(/is|this/g, '').split(" ");
That should remove "is" and "this" and then you can split it from there.
Update
Tweaked the regex just a bit. I forgot to add a g to make it get rid of all of them.
If you want it to be case-insensitive (i.e., match This, Is, etc.), add the i switch after the g.
5 Comments
["Th", "is", ...