Reputation: 2103
How to compare a string, may be already in variable, with element taken from DOM? with element like this
"Something here"
when i call this element with .text() method, i dont just get "Something here", but more like
"
Something
here
"
This is not a literal example, i mean my value is returned with additional whitespaces, and therefore i'm not able to compare it with anything, even if i copy whitespaced string from console.
EDIT
Pretty much all answers tell me to use $.trim, i tried it before and it doesnt work, doesnt remove all the whitespaces, still cant compare even with copy/paste from console.log
Upvotes: 0
Views: 966
Reputation: 5914
can you specify the version of jquery you're using (+ post your code maybe) ? I've checked a couple of answers and made my own check and they all seem to work just fine.
Upvotes: 0
Reputation: 1140
If you do not want a dependency on JQuery, you should instead use a regular expression:
"Some String" == element.innerHTML.replace(/^\s+|\s+$/g, '');
Upvotes: 0
Reputation: 388446
You can use trim() to remove the trailing and leading spaces then compare them..
$.trim(x.text()) == 'abc'
$.trim() is used instead of String.trim() because of IE support
Upvotes: 2
Reputation: 4293
Trim and Compare:
if("string_to_compare" == $.trim(element.text())) {
//some code
}
Upvotes: 3
Reputation: 148180
You can use $.trim to remove the spaces around the text you have.
$.trim($("selector").text())
The $.trim() function removes all newlines, spaces (including non-breaking spaces), and tabs from the beginning and end of the supplied string. If these whitespace characters occur in the middle of the string, they are preserved, jQuery Doc.
Upvotes: 1