view raw
supersize supersize - 11 months ago 42
jQuery Question

if .html() has specific value

this might be a very basic question, but I would like to know how I can find out if

has a particular value (in this case a string). An example:

<p id="text">Hello this is a long text with numbers like 01234567</p>

and I would like to ask

var $text = $('#text');
if ($text.html() == '01234567')

of course this would not work. But how can I enhance another method to
that asks

if($text.html().contains() == '01234567');

Important to say is, that in my case I definitely will search for things who are seperated with a space, not like
but indeed it would be interesting if that would work as well.

Thanks in advance!


As I understand from OP, these are the test cases:

hello12348hello     // false
hello 1234hello     // false
hello012348 hello   // false
hello 1234 hello    // TRUE
1234hello           // false
hello1234           // false
1234 hello          // TRUE
hello 1234          // TRUE
                    // false
1234                // TRUE
 1234               // TRUE

** Changing "" by any other white-space character (e.g. \t, \n, ...) should give same results.

As OP said:

for things who are separated with a space, not like withnumberslike01234567

So, hello 01234567withnumberslike is also wrong!!!

Creating the function:

function contains(value, searchString){
    // option 1: splitting and finding a word separated by white spaces
    var words = value.split(/\s+/g);
    for (var i = 0; i < words.length; i++){
        if (words[i] === searchString){
            return true;
    return false;

    // option 1a: for IE9+
    return value.split(/\s+/g).indexOf(searchString) > -1;

    // option 2: using RegEx
    return (new RegExp("\\b" + searchString + "\\b")).test(value);
    return (new RegExp("(^|\\s)" + searchString + "($|\\s)")).test(value);  // this also works

    // option 3: Hardcoded RegEx
    return /\b1234\b/.test(value);

See case tests here in jsFiddle

It will also accept tabs as well as whitespaces..

NOTE I wouldn't worry about using RegEx, it isn't fast as indexOf, but it stills really fast. It shouldn't be an issue, unless you iterate millions of times. If it would be the case, perhaps you'll need to rethink your approach because probably something is wrong..

I would say to you think about compatibility, there is a lot of users still using IE8, IE7, even IE6 (almost 10% right now - April, 2014). -- No longer an issue in 2016..

Also, it's preferred to maintain code standards.

Since, you are using jQuery you can use too .text() to find string:

var element = $(this);
var elementText = element.text();

if (contains(elementText, "1234"){
    element.text(elementText.replace("1234", "$ 1234.00"))
    $('#otherElement').text("matched: 1234");

Thanks to @Karl-Andr├ęGagnon for the tips.

\b: any boundary word (or start/end of the string)
^: start of the string
\s: Any whitespace character
$: end of the string