Search code examples
javascriptjqueryhtml-escape-characters

hyphen character comparison with —


I am trying to compare — with "-" but always getting false.

Referred this question : Comparing an emdash (—) in Javascript

Tried the jsfiddle link in the comment : https://jsfiddle.net/t16b7khb/. It works fine, but when i tried creating a new fiddle found that the hyphen i am entering is smaller than the one available in this jsfiddle. Not sure, whether the problem is with the OS, i am using macOS.

I have created a new fiddle by copy pasting the first 'if' from the comment and the second 'if' is typed by myself. jsfiddle link : https://jsfiddle.net/RajKumari_1/6n7pb5uh/

if( $("#element").text() == "—" ) {
    console.log('works for me')
}
if( $("#element").text() == "-" ) {
    console.log('not working for me')
} 

Thanks in advance.


Solution

  • Use localeCompare with sensitivity: 'base'

    if( $("#element").text().localeCompare('-', 'en', {sensitivity: 'base'}) ) {
        console.log('works for me')
    }
    

    Jsfiddle