Reputation: 43833
I'm working with some CMS system, and I have to paste HTML code (including CSS and JavaScript) in an editor.
The problem is it parses the input to validate html code. I have this piece of problematic code
keys.sort(function(a,b) {
if (a.position > b.position) return 1;
if (a.position < b.position) return -1;
return 0;
});
While it is valid JS syntax, the parser sees the <
and >
and says that is invalid syntax for html tags.
I'm wondering if JavaScript has another way to check for greater than or less than that doesn't use those <|>
symbols. Does anyone know?
Upvotes: 1
Views: 2552
Reputation: 15
You could replace unwanted characters with entities.
A php example:
$script = str_replace( "&", "&", $script );
$script = str_replace( "<", "<", $script );
$script = str_replace( ">", ">", $script );
Upvotes: 0
Reputation: 11805
Just made a funky javascript hack that will work for you:
function isLessThan(a, b) {
return Object.is((a-b)%1, -0);
}
function isGreaterThan(a, b) {
return a !== b && Object.is((a-b)%1, 0);
}
This seems to be because n%1
is either 0
or -0
depending on if n
is greater or equal to 0, or less than 0 respectively.
This is used like so:
keys.sort(function(a,b) {
if (isGreaterThan(a.position, b.position)) return 1;
if (isLessThan(a.position, b.position)) return -1;
return 0;
});
For your particular use case, I recommend:
keys.sort(function(a,b) { return a.position - b.position; })
Credit: Mike McCaughan
ref: checking +0 vs -0
Upvotes: 0
Reputation: 141839
In this particular case, and assuming the position
properties are number types, you could achieve the same sorting with:
keys.sort(function(a,b) {
return a.position - b.position;
});
However you should really look into solving the real issue here which may be with the CMS or with how you are using it. If the CMS is validating the input as XHTML for example you might need to use this trick: When is a CDATA section necessary within a script tag?
Now to answer the specific question in your title:
Is there a JavaScript alternative to greater than and less than?
For numbers, you could use Math.min as a >
and Math.max as a <
, like so:
keys.sort(function(a,b) {
if (Math.min(a.position,b.position) !== b.position) return 1;
if (Math.max(a.position,b.position) !== a.position) return -1;
return 0;
});
Upvotes: 4
Reputation: 13682
You can do this:
keys.sort(function(a,b) {
if (a.position > b.position) return 1;
if (a.position < b.position) return -1;
return 0;
});
That won't run properly as JavaScript code, but if you paste it into HTML, it will display properly.
Upvotes: 0