0

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

0

5 Answers 5

3

Trim and Compare:

if("string_to_compare" == $.trim(element.text())) {
    //some code
}
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

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.

Comments

0

If you do not want a dependency on JQuery, you should instead use a regular expression:

"Some String" == element.innerHTML.replace(/^\s+|\s+$/g, '');

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.