0

this might be a very basic question, but I would like to know how I can find out if .html() 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 .html() 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 withnumberslike01234567 but indeed it would be interesting if that would work as well.

Thanks in advance!

9
  • 4
    if($text.html().indexOf('01234567') != -1) {} developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Apr 10, 2014 at 20:35
  • Regarding spaces, simple solution: (' ' + .$text.html() + ' ').indexOf(' 01234567'). Commented Apr 10, 2014 at 20:38
  • @Scadoodles would this work as well, if there are no spaces in between? Commented Apr 10, 2014 at 20:38
  • and yes, contains() is a method in jquery. but not for what you are trying to do: api.jquery.com/jQuery.contains Commented Apr 10, 2014 at 20:39
  • 1
    @supersize: Why don't you have a look at the documentation that was linked to? (here again: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…). It describes how .indexOf works and provides examples. Commented Apr 10, 2014 at 20:43

5 Answers 5

3
(' ' + document.getElementById('text').textContent + ' ').indexOf(' 01234567 ') != -1

Fixes problem with the text at the beginning, doesn't abuse regex, and hooray for vanilla.js!

Sign up to request clarification or add additional context in comments.

4 Comments

I would use more variables, but sure.
now it's correct, but your vanilla.js won't work in IE<8 using textContent
You could use innerHTML if you need the support… but IE7 support isn't a requirement here.
@bjb568 yeah true, I think there should be a time when no one cares about that anymore. IE7, come one! Thanks for your answer, since Andre proved your example as completely right.
2

You can use indexOf:

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

if(text.indexOf(" 01234567") != -1) {
    // your logic
}

Your HTML might start with 01234567, though; in that case, you can do this:

if((' ' + text).indexOf(" 01234567") != -1) {
    // your logic
}

Thanks, bjb568 and Felix Kling.

9 Comments

What if 01234567 is at the beginning of the string?
you can put or condition
Yep. Need to add ' ' + text
@Gautam: How would this work with an OR condition? Do you want to test for ' 01234567' and '01234567'?
@FelixKling (' '+text).indexOf(" 01234567")!=-1 should work in that case
|
1

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"))
           .addClass("matchedString");
    $('#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

http://rubular.com/r/Ul6Ci4pcCf

18 Comments

@bjb568 Abuse of regex, what? This is exactly what regex is for. That DV and comment make absolutely no sense.
@supersize No. I don't know what that guy is spouting off about, but this is THE way to do it, IMO.
@bjb568 That isn't complicated, that is bad practice. How is the regex in this answer complicated? It is one identifier and a string. Also, the performance argument is pretty much moot: jsperf.com/regexp-test-search-vs-indexof/12 -- micro optimization at best in this use case. In this benchmark, regex outperforms all other approaches except direct comparison, which is not an option here.
Whatever that is supposed to mean -- your position is still flawed. RegEx is for string manipulation, it is the right tool for the job and performs better than indexOf. No one should give any credibility to claims that a simple pattern is "too complicated" for a simple match operation, the suggestion is demonstrably nonsensical.
|
0

You can use the String.indexOf method in JavaScript to determine whether or not one string is contained in another. If the string passed into indexOf is not in the string, then -1 is returned. This is the behavior you should utilize.

If ($test.html().indexOf("1234567890") != -1)
    //Do Something

2 Comments

EDIT: Haven't tested this code cause I'm on my phone but fairly confident in it's simplicity... :)
If is lowercase. This doesn't work if the string is asdf1234567890, it needs whitespace.
-1
if($text.html().indexOf('01234567') != -1) {

}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf

1 Comment

will return true for withnumberslike01234567

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.