2

I'm trying to separate string by multiple delimiters and include them in the result. Considering all consecutive non-whitespace characters as individual words. Example: "I'm working on a new super-project wow. Yay!" becomes "!Yay .wow project-super new a on working I'm" My code sofar:

function test(string){
    console.log(string.split(/([.'\!'+a-zA-Z]+)/g ).reverse().join(' ') );
}

var string ="I'm working on a new super-project wow. Yay!"
test(string)

the output so far is: Yay! wow. project - super new a on working I'm

I'm still getting the wrong result. Any help would be appreciated.

Roman
  • 1,118
  • 3
  • 15
  • 37
  • I hope this can help you. https://stackoverflow.com/questions/5993779/use-string-split-with-multiple-delimiters?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – Nicolas Takashi Apr 30 '18 at 19:48
  • Current accepted answer keeps `super-project` as is but it should be `project-super`. [Check this](https://stackoverflow.com/a/50107371/1020526). – revo Apr 30 '18 at 20:25
  • Roman, your *Considering all consecutive non-whitespace characters as individual words* requirement clashes with the expected result. My answer is in line with that requirement. Please make sure you selected the right answer as accepted. – Wiktor Stribiżew May 01 '18 at 19:50

2 Answers2

1

I suggest swapping words with the glued punctuation first (using .replace(/(^|\s)(\w+)([^\w\s]+)(?!\S)/g,"$1$3$2")) and then match all non-whitespace chunks and join with a space:

function test(string){
    console.log(string.replace(/(^|\s)(\w+)([^\w\s]+)(?!\S)/g,"$1$3$2").match(/\S+/g).reverse().join(' ') );
}
//"!Yay .wow project-super new a on working I'm"
var string ="I'm working on a new super-project wow. Yay!"
test(string)

The word-punctuation swapping regex details:

  • (^|\s) - Group 1: start of string or whitespace
  • (\w+) - Group 2: one or more word chars
  • ([^\w\s]+) - Group 3: any 1+ words other than word and whitespace chars
  • (?!\S) - no non-whitespace char is allowed immediately to the right of the current location. Together with (^|\s), these subpatterns form whitespace word boundaries.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

Rules are not so clear, there may be more cases to include but if not, splitting on [!?.\s-]+ (or whatever delimiters are) would be a solution. You don't need to hack into .replace() or .match() methods:

var str = "I'm working on a new super-project wow. Yay!";
console.log(str.split(/([!?.\s-])/g).reverse().join(''));
revo
  • 47,783
  • 14
  • 74
  • 117