Skip to main content
Known Participant
March 6, 2024
Answered

Split() text either by line breaks or spaces (" ")

  • March 6, 2024
  • 2 replies
  • 1872 views

Hi everyone,
I would like to split my source text up to single words. text.sourceText.split(" ") works, but it doesnt take line breaks into account. I thought this would be the solution:

text.sourceText.split(" ", "\r")

 I e splitting the text up either by spaces or line breaks, but it doesn't work.

What am I doing wrong?

Best,

Mikael

Correct answer Airweb_AE

You need to replace line breaks with spaces and then split spaces

 

 

text.sourceText.replace(/\r/g,"\r ").split(" ")

 

 

2 replies

Mylenium
Brainiac
March 6, 2024

Some simple regex trickery probably works just as well, since all string functions should handle regular expressions without explitly having to declare them:

 

text.sourceText.split(" "|"\r")

 

Mylenium

 

Known Participant
March 6, 2024

I thought I tried that, maybe I was just typing it wrong. But problem now solved, thank you!

Airweb_AECorrect answer
Brainiac
March 6, 2024

You need to replace line breaks with spaces and then split spaces

 

 

text.sourceText.replace(/\r/g,"\r ").split(" ")

 

 

Known Participant
March 6, 2024

I had tried something similar but that didn't work. After some troubeshooting I found that it only replaced the first instance of a linebreak. This is how I finally got it to work:

text.sourceText.replace(/\r/g, "\r ").split(" ")

 Thank you!