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!");
}
}
The error I’m getting in the Web Console is ‘Syntax Error: Illegal Character’.
Grateful for any ideas on how to solve this.
Thanks in advance.
There’s no need for a regular expression for that, just compare the element’s
innerHTMLproperty to"\\r", e.g.: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.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):