0

How I can convert string -

text = "test test1 \n \n \n \n \n \n \n \n \n \n \n \n \n \n test2 \n"

to

test test1 \n\n\n\n\n\n\n\n\n\n\n\n\n\n test2\n

I tried use next - text.gsub(/\s\n/, '\n'), but it added additional slash -

test test1\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n test2\\n

2 Answers 2

3

Use double quotes, instead of single:

text.gsub(/\s\n/, "\n")

With single quotes, \n has the meaning of \ and n, one after another. With double, it is interpreted as new line.

Sign up to request clarification or add additional context in comments.

2 Comments

With this there will be no space after test1
@Abhi, I think he didn't want to have space there and it was just mistake on his part. You can see that the space after test2 is expected to be removed. If he indeed wants to have the space, he should further clarify which spaces should be removed and which - not.
0

I expect that either the space after "test1" is to be removed as well or the space after "test2" is not to be removed. @ndn assumed the former was intended. If the second interpretation applies, you could do the following:

r = /
    (?<=\n) # match \n in a positive lookbehind
    \s      # match a whitespace character
    (?=\n)  # match \n in a positive lookahead
    /x      # extended/free-spacing regex definition mode

text.gsub(r,"")
    #=> "test test1 \n\n\n\n\n\n\n\n\n\n\n\n\n\n test2 \n"

or:

text.gsub(/\n\s(?=\n)/, "\n")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.