EN
JavaScript - find text in string
2 points
In JavaScript, it is possible to find text in strings with String
search
method.
String
search
method works in the following way:
- as the first argument takes a regular expression
- returns first text occurrence position,
- returns
-1
value if nothing found
xxxxxxxxxx
1
var text = 'This is my text...';
2
3
var position1 = text.search('is'); // be careful because of regex characters
4
var position2 = text.search('\\bis\\b');
5
6
console.log(position1); // 2
7
console.log(position2); // 5
xxxxxxxxxx
1
var text = 'This is my text...';
2
var position = text.search(/\bis\b/);
3
4
console.log(position); // 5