You can simply split on space and all unwanted characters:
var sentence = "the quick, brown fox; jumped (over) the fence."
var seen = {};
var result = sentence
.split(/[ ,;\(\)\.]+/)
.sort()
.filter(Boolean)
.filter((word) => {
if(seen[word]) {
return false;
}
seen[word] = 1;
return true;
});
console.log('result: ' + result.join(', '));
Console output:
result: brown, fence, fox, jumped, over, quick, the
Explanation:
.split(/[ ,;\(\)\.]+/)
– split on space and all unwanted characters.sort()
– sort the array.filter(Boolean)
– remove empy array items.filter((word) => {...})
– filter out duplicates using aseen
object
You did not ask for the sort and filter, but I thought this might be useful for your case.
CLICK HERE to find out more related problems solutions.