用行分隔符(Javascript)替换文本区域中的 <br />
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15225321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replace <br /> in a textarea with a line separator ( Javascript )
提问by Igor L.
I guess this will be answered in two minutes but I am not able to google out a solution.
我想这将在两分钟内得到回答,但我无法通过谷歌搜索解决方案。
I have a textarea which first recieves some data from the server (dynamically using AJAX). The text in the textarea may look like this:
我有一个 textarea,它首先从服务器接收一些数据(动态使用 AJAX)。textarea 中的文本可能如下所示:
Hello Cruel <br />World!
My users do not like the look of this :)
我的用户不喜欢这个外观:)
So I wrote a very simple function:
所以我写了一个非常简单的函数:
function replaceHtml( string_to_replace )
{
var result = replaceAll( string_to_replace, " ", " ");
result = result.replace(/<br\s*\/?>/mg,"\n\r"); // or "\n", "\r", "\r\n"
return result;
}
My output looks like this:
我的输出如下所示:
Hello Cruel World!
Instead of:
代替:
Hello Cruel
World!
I would love a solution that is at most 5 lines long and can be applied with all browsers and OSes
我想要一个最多 5 行长的解决方案,并且可以应用于所有浏览器和操作系统
Btw, Im no fan of regexes, so maybe the real problem will be there..
顺便说一句,我不喜欢正则表达式,所以也许真正的问题会在那里..
UPDATE
更新
From this answerand mr Michael_B I got this solution, which is working for me, but I've got a hunch the character might not be the best solution there is:
从这个答案和 Michael_B 先生我得到了这个对我有用的解决方案,但我有一种预感,这个角色可能不是最好的解决方案:
function replaceHtml( string_to_replace )
{
return string_to_replace.replace(/ /g, ' ').replace(/<br.*?>/g, '\u2028');
}
回答by Kaizen Programmer
Based on @Explosion Pills comment and jsFiddle
基于@Explosion Pills 评论和 jsFiddle
function replaceHtml( string_to_replace )
{
return string_to_replace.replace(/ /g, ' ').replace(/<br.*?>/g, '\n');
}
UPDATEbased on New line in text area
基于文本区域中的新行更新
Maybe this will fix your issue with \n
- Requires jQuery.
也许这会解决您的问题\n
- 需要 jQuery。
function replaceHtml(string_to_replace) {
return $("<div>").append(string_to_replace.replace(/ /g, ' ').replace(/<br.*?>/g, ' ')).text();
}
回答by Matt Fletcher
Correct me if I'm wrong, but should it not be $.replaceAll()
as it's a jQuery function not JS?
如果我错了,请纠正我,但不应该$.replaceAll()
因为它是 jQuery 函数而不是 JS 吗?
Or replace()
in pure Javascript?
还是replace()
在纯 Javascript 中?
回答by Charlotte
You didn't need to use jQuery in there:
你不需要在那里使用 jQuery:
function replaceHtml( string_to_replace )
{
var result = string_to_replace.replace(/\ /g, ' ').replace(/<br\s*\/?>/mg,"\n\r"); // or "\n", "\r", "\r\n"
return result;
}