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!

supersize
  • 13,764
  • 18
  • 74
  • 133
  • 4
    if($text.html().indexOf('01234567') != -1) {} https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf – Scadoodles Apr 10 '14 at 20:35
  • Regarding spaces, simple solution: `(' ' + .$text.html() + ' ').indexOf(' 01234567')`. – Felix Kling Apr 10 '14 at 20:38
  • @Scadoodles would this work as well, if there are no spaces in between? – supersize Apr 10 '14 at 20:38
  • and yes, contains() is a method in jquery. but not for what you are trying to do: https://api.jquery.com/jQuery.contains/ – Scadoodles Apr 10 '14 at 20:39
  • @supersize Could you clarify what you mean about the spaces? Do you mean it's ok if there are sometimes spaces separating, or do you only want space-separated strings? – Milo P Apr 10 '14 at 20:39
  • @supersize: `.indexOf` just looks where a string is contained in another string. Nothing else. – Felix Kling Apr 10 '14 at 20:41
  • 1
    @supersize: Why don't you have a look at the documentation that was linked to? (here again: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf). It describes how `.indexOf` works and provides examples. – Felix Kling Apr 10 '14 at 20:43
  • yes, it should work the same, that is why the conditional is != -1 – Scadoodles Apr 10 '14 at 20:43
  • thanks guys! worked, is there one problem left since @Scadoodles didn't make it as answer who to accept? – supersize Apr 10 '14 at 20:45

5 Answers5

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!

bjb568
  • 11,089
  • 11
  • 50
  • 71
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.

Ry-
  • 218,210
  • 55
  • 464
  • 476
Gautam
  • 3,276
  • 4
  • 31
  • 53
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

Andre Figueiredo
  • 12,930
  • 8
  • 48
  • 74
  • 2
    @bjb568 Abuse of regex, what? This is exactly what regex is for. That DV and comment make absolutely no sense. – Chris Baker Apr 10 '14 at 20:39
  • does regex have an disadvantage? – supersize Apr 10 '14 at 20:39
  • 2
    @supersize No. I don't know what that guy is spouting off about, but this is THE way to do it, IMO. – Chris Baker Apr 10 '14 at 20:40
  • 1
    You are working with text, regex is not necessary. The problem with regex is that it's complicated and slow - it's fine for complicated tasks, but this is a simple string so it is not required. – bjb568 Apr 10 '14 at 20:41
  • 1
    Saying something is "complicated" is no reason. Programming is complicated, until you learn how to do it. Regex's strength is working with text. – Chris Baker Apr 10 '14 at 20:42
  • 2
    abuse?? read this: http://blog.codinghorror.com/regex-use-vs-regex-abuse/ http://programmers.stackexchange.com/questions/113237/when-you-should-not-use-regular-expressions – Andre Figueiredo Apr 10 '14 at 20:45
  • 2
    @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: http://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. – Chris Baker Apr 10 '14 at 20:46
  • That's exactly what I'd say. If there is no reason to do something, don't do it. Regex is unnatural for this: if you want to compare strings, do so. jQ is unnatural for this: if you want to use JS, do so. Without bloatware. – bjb568 Apr 10 '14 at 20:48
  • @bjb568 RegEx **is** natural for this!! – Andre Figueiredo Apr 10 '14 at 20:55
  • 2
    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. – Chris Baker Apr 10 '14 at 20:59
  • 1
    @bjb568 will all due respect, I like vanilla-js too, but you wrong! Read carefully question. Tell me, you'd prefer save **microseconds** than maintainability and readability?? – Andre Figueiredo Apr 10 '14 at 21:12
  • Is my answer unreadable? Seriously? Take a space, add it to the textContent of text, get the indexOf ' 01234567' and make sure it isn't -1 (doesn't exist). Seems straight forward. Please comment on my answer under my answer. – bjb568 Apr 10 '14 at 21:14
  • 2
    Im LMAO'ing overhere. @AndréFigueiredo About your answer, your split should use regexp since you will have empty array when there is multiple space : `value.split(/\s+/g);`. You regexp solution can simply be `"\b" + searchString + "\b"`. It will work if the word is followed by punctuation, back, line break, etc etc... As for the regexp debat, it doesnt matter in this case, but sometime regexp are slow if they are not optimized. – Karl-André Gagnon Apr 10 '14 at 21:15
  • @Karl-André Gagnon thanks for the reminders... you're right, they're better snippets.. I will update the answer – Andre Figueiredo Apr 10 '14 at 21:23
  • 1
    Your option 1 is okay, though you can just use `Array.prototype.indexOf` to do the check (unless it’s for IE≤8 compatibility?). Avoid the error-squashing `typeof` check, by the way. Yes, dynamic regular expressions are usually abuse of regular expressions, and you may note that neither of them will work if you’re searching for, say, a parenthesis. It’s too bad there’s no built-in escape… – Ry- Apr 10 '14 at 21:34
  • wait wait guys, thats getting to complicated to me here. So to break that down, I want a solution which works definitely for every kind of string and even when its seperated by spaces. So my question, andre, is. Does the accepted answer is guaranteed to work? Thanks – supersize Apr 11 '14 at 01:51
  • 1
    @AndréFigueiredo thanks, now I get it! And thanks for the different ways to have an overview! – supersize Apr 11 '14 at 10:33
  • LOL man, somehow a got here after 2 years... I vital thing that I have to add why I wrote this solution as it is: I thought a RegExp because of ease of the whitespace matcher will split other "white-spaces" e.g. `\t`. That is in the test cases... – Andre Figueiredo Jun 09 '16 at 15:00
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
Luke Joshua Park
  • 9,527
  • 5
  • 27
  • 44
-1
if($text.html().indexOf('01234567') != -1) {

}

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

Scadoodles
  • 151
  • 6