How can you determine that the line has the desired text?

How does the string contain a substring in javascript?

  • association: stackoverflow.com/questions/1789945 - user207618
  • and what is the secret meaning of publishing question-answer translations, even without mentioning the author of the original answer and linking to it? Okay, such a connection would be maintained at the level of CO and the reputation of the original answer went. And so dubious initiative with the creation of fake questions. - teran

1 answer 1

There are actually quite a few ways:

  1. String#indexOf(str: String[, fromIndex: Number]): Number is one of the oldest ways.

    Returns the position found str or, if the substring is not found, -1 .
    The fromIndex parameter specifies the indent for the search.

    Important: In the condition it is necessary to use a comparison and be sure to strict:

    1. Without comparison, -1 (no substring) is treated as true .
    2. May return 0 (matched the first character), which is normal comparison to false .

       'Hello, world!'.indexOf('world'); // 7 'Hello, world!'.indexOf('o'); // 4, в конце hello 'Hello, world!'.indexOf('o', 5); // 8, вторая буква в world !!'Hello, world!'.indexOf('z'); // true, отрицательное число приводится к true !!'Hello, world!'.indexOf('H'); // false, 0 трактуется как false 
  2. String#search([regexp: RegExp]): Number - the same String#indexOf , only with a regular expression and no offset.

     "Date of birth of Einstein: 3/14/1879".search(/\d{4}/); // 32 
  3. String#includes(searchString: String[, position: Number]): Boolean is a kosher version of String#indexOf with two differences:

    1. Returns a Boolean , instead of a position, which may be more expected.
    2. It works faster. However, the difference is palpable only on very large volumes, check .

       'Hello, world!'.includes('o'); // true, в конце hello 'Hello, world!'.includes('o', 9); // false, после девятого символа нет 'o' 
  4. String#match(regexp: RegExp): Array | Null String#match(regexp: RegExp): Array | Null - String#search on steroids (however, slower).

    Returns a slightly modified array with the found substring, the position of the match ( index ) and the input property - the string in which the search took place or Null , if the regular program did not find anything.
    Optionally, in the array can be captured groups.
    When using the g flag, all found matches will be returned (though without groups and special properties):

     "Date of birth of Einstein: 3/14/1879".match(/(\d{4})/); // [0: "1879", 1: "1879", index: 32, input: "Date of birth of Einstein: 3/14/1879", length: 2] `Date of birth of Einstein: 3/14/1879; Date of birth of Hendrik Lorentz: 7/18/1853`.match(/(\d)\/(\d{2})\/(\d{4})/g); // [0: "3/14/1879", 1: "7/18/1853", length: 2] 

There are also methods RegExp#test or RegExp#exec , which can also be used for testing, but this is another story.