Javascript can convert strings into a String
object, which includes:
String.length
property representing the number of characters in the string.Find the 'length' of a string
const browserType = 'mozilla';
browserType.length; // 7
Retrieving a specific string character
const firstChar = browserType[0];
console.log(firstChar); // 'm'
Retrieving the last character
const lastChar = browserType[browserType.length - 1];
console.log(lastChar); // 'a'
The includes()
method performs a case-sensitive search to determine whether one string may be found within another string, returning true
or false
as appropriate.
const browserType = 'mozilla';
if (browserType.includes('zilla')) {
console.log('Found zilla!');
} else {
console.log('No zilla here!');
}
The startsWith()
method determines whether a string begins with the characters of a specified string, returning true or false as appropriate.
const browserType = 'mozilla';
if (browserType.startsWith('moz')) {
console.log('Starts with moz!');
} else {
console.log("Doesn't start with moz!");
}
The endsWith()
method determines whether a string ends with the characters of a specified string, returning true
or false
as appropriate.
const browserType = 'mozilla';
if (browserType.endsWith('zilla')) {
console.log('Ends with zilla!');
} else {
console.log("Doesn't end with moz!");
}
The indexOf()
method, given one argument: a substring to search for, searches the entire calling string, and returns the index of the first occurrence of the specified substring.
const paragraph = 'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?';
const searchTerm = 'dog';
const indexOfFirst = paragraph.indexOf(searchTerm);
console.log(`The index of the first "${searchTerm}" from the beginning is ${indexOfFirst}`);
// expected output: "The index of the first "dog" from the beginning is 40"
The replace()
method returns a new string with some or all matches of a pattern
replaced by a replacement
.
const browserType = 'mozilla';
const updated = browserType.replace('moz','van');
console.log(updated); // "vanilla"
console.log(browserType); // "mozilla"
The slice()
method extracts a section of a string and returns it as a new string, without modifying the original string.
const browserType = 'mozilla';
console.log(browserType.slice(1, 4)); // "ozi"