浏览器中的Javascript Regex Substitution换行处理 [英] Javascript Regex Substitution newline handling in browsers

查看:69
本文介绍了浏览器中的Javascript Regex Substitution换行处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个html文本区域,该区域可以在其中输入的任何文本的开头和结尾添加"["和]".

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

我的问题是,当我在文本区域中输入一些多行数据时,正则表达式在ff和ie中的处理方式有所不同.

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

输入:

Iam
learning
regex

预期的输出:(我在FF中得到了

Expected Output: (I get this in FF )

[Iam]
[learning]
[regex]

IE中的输出:

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

正则表达式代码在这里:

The Regex code is here:

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

我在正则表达式中添加了(\n{0,})以匹配换行符..但是它没有任何作用..

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

谢谢

推荐答案

在IE中,textarea的value属性中的行分隔符为\r\n.在所有其他主要浏览器中,它都是\n.一个简单的解决方案是首先将行分隔符归一化为\n.我还简化了正则表达式:

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]");

这篇关于浏览器中的Javascript Regex Substitution换行处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆