Skip to main content
Known Participant
Mar 6, 2024 1:41 PM UTC
Answered

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

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

Airweb_AECorrect answer
Legend
Mar 6, 2024 1:54 PM UTC

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

 

 

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

 

 

5 replies

Mylenium
Legend
Mar 6, 2024 2:56 PM UTC

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

 

Translate
Known Participant
Mar 6, 2024 3:18 PM UTC

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

Translate
Airweb_AECorrect answer
Legend
Mar 6, 2024 1:54 PM UTC

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

 

 

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

 

 

Translate
Known Participant
Mar 6, 2024 3:13 PM UTC

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!

Translate