正则表达式匹配Javascript中的回车 [英] Regex to match carriage return in Javascript
问题描述
我正在尝试编写一些Javascript来隐藏一些仅包含回车符的元素。我理解解决这个问题的正确方法是停止创建这些元素,但不幸的是,在这种情况下这是不可能的。我正在尝试使用正则表达式来搜索不需要的元素但是没有太多运气。我写的函数如下:
I am trying to write some Javascript to hide some elements that contain only carriage returns. I appreciate that the correct way to solve this problem would be to stop these elements being created, but unfortunately that is not possible in this instance. I am trying to user a regular expression to search for the unwanted elements but am not having much luck. The function I have written is as follows:
function HideEmptyP()
{
var patt = (\\r)
for(var i = 0;i<desc[i].length;i++);
{
var desc[i] = document.getElementsByClassName('sitspagedesc');
var result[i] = patt.test(desc[i]);
if (result[i] == true)
{
desc[i].style.display='none';
}
else
{
alert("No Match!");
}
}
我在Web控制台中收到的错误是'语法错误:非法字符'。
The error I'm getting in the Web Console is 'Syntax Error: Illegal Character'.
感谢有关如何解决此问题的任何想法。
Grateful for any ideas on how to solve this.
提前致谢。
推荐答案
我正在尝试编写一些Javascript来隐藏一些只包含回车的元素。
I am trying to write some Javascript to hide some elements that contain only carriage returns.
不需要正则表达式,只需将元素的 innerHTML
属性与<$ c $进行比较c>\\\\,例如:
There's no need for a regular expression for that, just compare the element's innerHTML
property to "\\r"
, e.g.:
if (demo[i].innerHTML === "\\r") {
// Remove it
}
但请注意,某些浏览器可能会转换单个回车符。您可能想要检查\\\\
,\\ n
,并且只是空间。要做到这一点,你可能想要使用正则表达式。
But beware that some browsers may transform a single carriage return. You might want to check for "\\r"
, "\\n"
, and just a space. To do that, you might want to use a regular expression.
你的正则表达式文字((\\\ \\ r)
)完全无效,值得阅读它们了解正确的语法。要在JavaScript中编写正则表达式文字,可以使用 /
作为分隔符。所以: / \\r /
。要测试字符串是否仅包含 \ r
, \ n
或空格,您可以使用 / ^ [\\\ n] + $ /
(要求至少有一个匹配的字符,并使用 ^
表示字符串开头, $
表示字符串结束):
Your regular expression literal ((\\r)
) is just completely invalid, it's worth reading up on them to learn the correct syntax. To write a regular expression literal in JavaScript, you use /
as the delimiter. So: /\\r/
. To test that a string contains only \r
, \n
, or space, you can use /^[\r\n ]+$/
(which requires there be at least one character that matches, and uses ^
to indicate start-of-string, and $
to indicate end-of-string):
if (demo[i].innerHTML.match(/^[\r\n ]+$/) {
// Remove it
}
这篇关于正则表达式匹配Javascript中的回车的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!