Comparing whether a unicode equals something [clos

2019-09-21 19:53发布

I'd like to add some logic to my code along the lines of:

var X = $('span').text()
$('body').append(X)

if (X == '▼') {
  $('body').append('Yay!')
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>&#9660;</span>

However, as you can see from the above snippet, "Yay!" isn't appended to the body. So how can I check if a unicode character equals an escape sequence?

3条回答
欢心
2楼-- · 2019-09-21 20:05

Use charCodeAt(0) and omit the '&#' in your string:

if ( X.charCodeAt(0) == 9660 ) {
  $('body').append('Yay!');
}
查看更多
Juvenile、少年°
3楼-- · 2019-09-21 20:25

In javascript you can escape unicode characters with \u followed by the hexidecimal representation of the unicode value. See this for the conversion of your character. Near the bottom of the page it gives the Java escape code for the character which is the same as the JavaScript one.

var X = $('span').text()
$('body').append(X)
if (X == '\u25bc') {
  $('body').append('Yay!')
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>&#9660;</span>

查看更多
不美不萌又怎样
4楼-- · 2019-09-21 20:29

You can use String.fromCharCode() to create the character using the decimal number so that it matches the HTML entity you're using. Or just copy the character into a string literal and compare directly. This may be clearer or not depending on your situation.

var X = $('span').text()
$('body').append(X)


if (X == String.fromCharCode(9660)) {
  $('body').append('Yay!')
}

if (X == "▼") {
  $('body').append('Yay!')
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>&#9660;</span>

查看更多
登录 后发表回答