String methods in Javascript
Working with strings is tricky in Javascript, but the old way, using primitive string literals is a safe solution. The compiler automatically converts the primitives to String objects, you can use the String object methods without the risk of immutability.
Testing strings
JavaScript provides easy to use built in tools for testing string. Please use them careful, they are all case sensitive!
let text = 'Hello world';
console.log(text.startsWith('hell')); // false
console.log(text.endsWith('world')); // true
console.log(text.includes('ell')); // trueAdvanced search for parts of the strings
There are more advanced tools if you have to solve complex tests or find a part of a string. The performance comparisons point to the benefits of indexOf method. This method has two parameters, a string what you want to find and an optional fromIndex, from where we are trying to find the pattern.
Get Tamás Kovács’s stories in your inbox
Join Medium for free to get updates from this writer.
The method returns the index of the searched string or returns with -1 when there is no match.
let text = 'HelloHelloHelloHello';
let first = text.indexOf('Hello'); // 0
let second = text.indexOf('Hello', first+1); // 5
let third = text.indexOf('Hello', second+1); // 10The search method returns the same result, but it has only one parameter a RegExp object, you can't set the starting index.
let text = 'Hello Bello Bro';
let position = text.search(/Bello/g); // 6The match method provides more possibilites, you get the whole resultset or null.
var text = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
var result = text.match(/[A-E]/gi);/* result
["A", "B", "C", "D", "E", "a", "b", "c", "d", "e"]
*/let secondText = 'For more information, see Chapter 3.4.5.1';
let resultSet = secondText.match(/see (chapter \d+(\.\d)*)/i);/* resultSet
{
0: "see Chapter 3.4.5.1",
1: "Chapter 3.4.5.1",
2: ".1", index: 22,
input: "For more information, see Chapter 3.4.5.1"
}
*/
There are numerous String methods what you have to know and use in your daily work. We will check the string manipulation methods in my next article.








