删除断线
我以前问过这个问题,但我似乎没有得到正确的答案。我遇到了文本中新行的问题。 Javascript 和 jQuery 不喜欢这样的事情:
alert('text
text);
当我从包含断行的数据库表中提取信息时,JS 和 jQuery 无法正确解析它。我被告知要使用 n2lbr(),但是当有人在消息中输入文本时使用“shift+enter”或“enter”时,这不起作用(这就是我遇到此问题的地方)。我在使用它时仍然会出现单独的行。它似乎在换行符之后正确应用了 BR 标记,但它仍然在那里留下了换行符。
有人可以在这里提供一些帮助吗?我使用 jQuery 获取消息数据并将其发送到 PHP 文件进行存储,所以我想解决那里的问题。
这通常不会成为问题,但我想在用户第一次加载收件箱时提取所有用户消息,然后在他们选择某个消息时通过 jQuery 将其显示给他们。
I've asked this question before but I didn't seem to get the right answer. I've got a problem with new lines in text. Javascript and jQuery don't like things like this:
alert('text
text);
When I pull information from a database table that has a break line in it, JS and jQuery can't parse it correctly. I've been told to use n2lbr(), but that doesn't work when someone uses 'shift+enter' or 'enter' when typing text into a message (which is where I get this problem). I still end up with separate lines when using it. It seems to correctly apply the BR tag after the line break, but it still leaves the break there.
Can anyone provide some help here? I get the message data with jQuery and send it off to PHP file to storage, so I'd like to fix the problem there.
This wouldn't be a problem normally, but I want to pull all of a users messages when they first load up their inbox and then display it to them via jQuery when they select a certain message.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用正则表达式将换行符替换为空格:
m
修饰符将跨换行符匹配,在本例中我认为这很重要。编辑:抱歉,没有意识到您实际上想要
元素,而不是空格。相应地更新了答案。edit2:像@LainIwakura一样,我在正则表达式中犯了一个错误,部分原因是之前的编辑。我的新正则表达式仅替换 CR/NL/LF 字符,而不替换任何空白字符 (
\s
)。请注意,有一堆我尚未确认的 unicode 换行符 字符...如果您需要处理这些问题,您可能需要阅读 regexp 语法对于unicodeYou could use a regexp to replace newlines with spaces:
The
m
modifier will match across newlines, which in this case I think is important.edit: sorry, didn't realise you actually wanted
<br />
elements, not spaces. updated answer accordingly.edit2: like @LainIwakura, I made a mistake in my regexp, partly due to the previous edit. my new regexp only replaces CR/NL/LF characters, not any whitespace character (
\s
). note there are a bunch of unicode linebreak characters that i haven't acknowledged... if you need to deal with these, you might want to read up on the regexp syntax for unicode编辑:好吧,在我自己绊倒了很多次之后,我相信你想要这个:
然后我就去睡觉了……太晚了,无法回答问题。
Edit: Okay after much tripping over myself I believe you want this:
And with that I'm going to bed...too late to be answering questions.
我通常使用
json_encode()
来格式化字符串以便在 JavaScript 中使用,因为它执行使 JS 有效 值所需的一切操作。I usually use
json_encode()
to format string for use in JavaScript, as it does everything that's necessary for making JS-valid value.