How can you determine that the line has the desired text?
- 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
- @teran, ru.meta.stackoverflow.com/questions/70 - user207618
1 answer
There are actually quite a few ways:
String#indexOf(str: String[, fromIndex: Number]): Numberis one of the oldest ways.Returns the position found
stror, if the substring is not found,-1.
ThefromIndexparameter specifies the indent for the search.Important: In the condition it is necessary to use a comparison and be sure to strict:
- Without comparison,
-1(no substring) is treated astrue. May return
0(matched the first character), which is normal comparison tofalse.'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
- Without comparison,
String#search([regexp: RegExp]): Number- the sameString#indexOf, only with a regular expression and no offset."Date of birth of Einstein: 3/14/1879".search(/\d{4}/); // 32String#includes(searchString: String[, position: Number]): Booleanis a kosher version ofString#indexOfwith two differences:- Returns a
Boolean, instead of a position, which may be more expected. 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'
- Returns a
String#match(regexp: RegExp): Array | NullString#match(regexp: RegExp): Array | Null-String#searchon steroids (however, slower).Returns a slightly modified array with the found substring, the position of the match (
index) and theinputproperty - the string in which the search took place orNull, if the regular program did not find anything.
Optionally, in the array can be captured groups.
When using thegflag, 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.
- And why did you ask a question and answered it yourself? : D - E1mir
- @KryTer_NexT, Can I answer my question? - vp_arth