Sekhar
Sekhar

Reputation: 5787

Javascript Regex Substitution newline handling in browsers

I created a html textarea with a capability to add "[" and "]" at the beginning and end of whatever text has been entered within that.

My problem is, when I enter some multiline data into the textarea, the regex is handled differently in ff and ie.

Input:

Iam
learning
regex

Expected Output: (I get this in FF )

[Iam]
[learning]
[regex]

Output in IE:

[Iam
][]
[learning
][]
[regex]

The Regex code is here:

(textareaIDelement.value).replace(/(^)(.*)(\n{0,})($)/gm, "[" + "$2" +"]");

I added the (\n{0,}) in the regex to match newlines.. but it doesn't have any effect..

Thanks

Upvotes: 0

Views: 1732

Answers (2)

Tim Down
Tim Down

Reputation: 324567

In IE, the line separator in a textarea's value property is \r\n. In all other major browsers it's \n. A simple solution would be to normalize line separators into \n first. I've also simplified the regex:

textareaIDelement.value.replace(/\r\n/g, "\n").replace(/^(.*)\n*$/gm, "[$1]");

Upvotes: 3

Andrzej Doyle
Andrzej Doyle

Reputation: 103797

My guess is that Firefox is using a single 0x0A (\n) as the line separator, whereas IE is using the Windows separator 0x0D 0x0A (\r\n).

Depending on the exact semantics of the regex library, it's probably matching both of the WIndows characters independently as line separators, hence it detects the end of the line followed by a 0-character line.

(This isn't an actual answer per se, as I'm not massively familiar with exactly how JS processes regex metacharacters, but hopefully it will point you in the right direction.)

Upvotes: 1

Related Questions