简体   繁体   中英

Is there a JavaScript alternative to greater than and less than?

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?

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;
    });

You can do this:

    keys.sort(function(a,b) {
        if (a.position &gt; b.position) return 1;
        if (a.position &lt; 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.

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

You could replace unwanted characters with entities.

A php example:

$script = str_replace( "&", "&amp;", $script );
$script = str_replace( "<", "&lt;", $script );
$script = str_replace( ">", "&gt;", $script );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM