Exit
  • Global community
    • Language:
      • Deutsch
      • English
      • Español
      • Français
      • Português
  • 日本語コミュニティ
  • 한국 커뮤니티
0

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

Explorer ,
Mar 06, 2024 Mar 06, 2024

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

TOPICS
Expressions
1.7K
Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines

correct answers 1 Correct answer

Advocate , Mar 06, 2024 Mar 06, 2024

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

 

 

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

 

 

Translate
Advocate ,
Mar 06, 2024 Mar 06, 2024

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

 

 

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

 

 

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Explorer ,
Mar 06, 2024 Mar 06, 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!

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Explorer ,
Mar 06, 2024 Mar 06, 2024

The "g" for global (to keep replacing line breaks after the first instance. The "\r " (including a space) since I wanted to keep the line break.

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
LEGEND ,
Mar 06, 2024 Mar 06, 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

 

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Explorer ,
Mar 06, 2024 Mar 06, 2024
LATEST

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

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines