1

I have this JS function that I'm trying to translate to Go:

function splitByEmptyNewline(str) {
  return str
    .replace(/\r\n/g, '\n')
    .split(/^\s*\n/gm);
}

Here's what I got so far:

func splitByEmptyNewline(str string) []string {
    strNormalized := regexp.
        MustCompile("\r\n").
        ReplaceAllString(str, "\n")
    return regexp.
        MustCompile("^s*\n").
        Split(strNormalized, -1)
}

This does not return the same result as the JavaScript version. So I'm wondering what I've missed?

I've tried using both double-quotes " and backward single-quotes ` for the regex.

1
  • Can you make the JS one into a StackSnippet with sample input output? Commented Apr 30, 2016 at 17:37

1 Answer 1

2

Your seperator RegEx does not match because you split a complete string and the beginning of that string is not white-space. So instead of ^\s*\n you must use \n\s*\n:

func splitByEmptyNewline(str string) []string {
    strNormalized := regexp.
        MustCompile("\r\n").
        ReplaceAllString(str, "\n")

    return regexp.
        MustCompile(`\n\s*\n`).
        Split(strNormalized, -1)

}

Here here is working example: https://play.golang.org/p/be6Mf3-XNP

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

1 Comment

Rather than a regular expression, why not simply remove the windows return? strNormalized := strings.Replace(str, "\r", "", -1)

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.