String
According to MDN Web Docs,
The String object is used to represent and manipulate a sequence of characters.
It would be impossible to write code without using a string. Strings are a part of every programmer's life.
For manipulating strings, JavaScript provides various functions and methods.
With these methods, developers can modify string values, determine character indexes, and change string cases. And so on.
This article will show some commonly used methods for manipulating strings in JavaScript:
includes()
includes()
method lets us determine whether or not a string includes another string.
Syntax
str.includes(searchString, position);
Parameters
searchString
String to search within str
. Regex cannot be used.
position
In the string, the location at which to begin searching for searchString. The default value is 0.
Example
const sentence = "The dog is mine";
const word = "dog";
console.log(
`The word "${word}" ${
sentence.includes(word) ? "is" : "is not"
} in the sentence`
);
// expected output: "The word "dog" is in the sentence"
charAt()
The charAt()
method returns a character in a string at a specific index (position).
The first character has an index of 0 the second has an index of 1
Syntax
str.charAt(index);
Example
const sentence = "The house is mine";
const index = 4;
console.log(`The character at index ${index} is ${sentence.charAt(index)}`);
// expected output: "The character at index 4 is h"
concat()
The concat()
method combines strings (str1, str2, /_ …, _/ strN) into one. Upon concatenating the string arguments, it returns a new string.
Syntax
str.concat(str2);
str.concat(str2, str3);
str.concat(str2, str3, ... , strN);
Example
const str1 = "Text";
const str2 = "Book";
console.log(str1.concat(" ", str2));
// expected output: "Text Book"
console.log(str2.concat(", ", str1));
// expected output: "Text, Book"
endsWith()
The endsWith()
method returns true if a string ends with a specified string. Otherwise, it returns false.
Syntax
str.endsWith(searchvalue, length);
Example
const str1 = "Dogs are the best!";
console.log(str1.endsWith("best!"));
// expected output: true
console.log(str1.endsWith("best", 17));
// expected output: true
const str2 = "Are you ok?";
console.log(str2.endsWith("ok"));
// expected output: false
indexOf()
The indexOf()
method returns the position of the first occurrence of a value in a string.
If the value cannot be found, indexOf()
returns -1.
It is important to note that indexOf()
is case sensitive.
Syntax
str.indexOf(searchvalue, position);
Parameters
searchString
Substring to search for.
position
In cases where position
exceeds the length of the calling string, the method skips the calling string altogether. Methods treat position
less than zero as if it were 0.
Example
const myString = "Hello World";
const myCapString = "Hello Nigeria";
console.log(`myString.indexOf("World") is ${myString.indexOf("World")}`);
// logs 6
console.log(`myCapString.indexOf("World") is ${myCapString.indexOf("World")}`);
// logs -1
lastIndexOf()
In a string, lastIndexOf()
returns the last occurrence (position
) of a value.
A string is searched from the end to the beginning using the lastIndexOf()
method.
lastIndexOf()
method returns the index from the beginning (position o
).
Syntax
str.indexOf(searchvalue, position);
Parameters
searchString
Substring to search for.
position
As a default, position
is defaulted to +Infinity
, which is the index of the last instance of the specified substring.
Example
const paragraph = "In the end, we all felt like we ate too much.";
const searchTerm = "ate";
console.log(
`The index of the first "${searchTerm}" from the end is ${paragraph.lastIndexOf(
searchTerm
)}`
);
// expected output: "The index of the first "ate" from the end is 32"
repeat()
The repeat()
method returns a new string containing the number of concatenated copies of the string that was passed in.
Syntax
str.repeat(count);
Example
const chorus = "until the night is over. ";
console.log(
`Chorus lyrics for "I wanna be in your life until the night is over": ${chorus.repeat(
7
)}`
);
//Chorus lyrics for "I wanna be in your life until the night is over": until the night is over. until the night is over. until the night is over. until the night is over. until the night is over. until the night is over. until the night is over.
replace()
replace()
method searches for values in a string or regular expressions in a string.
The replace()
method returns a newly created string with the replaced value(s).
replace()
does not alter the original string.
Syntax
str.replace(pattern, replacement);
Parameters
pattern
A regular expression is a typical example of a string or an object with the Symbol.replace
method. Values without the Symbol.replace
method will be converted to strings.
replacement
This can be a string or a function.
Example
const p = "The envelope is bad";
console.log(p.replace("is", "was"));
// The envelope was bad
const regex = /The/i;
console.log(p.replace(regex, "My"));
// My envelope is bad
search()
The search()
method searches for a word in the string and returns its index. If no match is found, it returns -1.
It is important to note that search()
is case sensitive.
Syntax
str.search(searchValue);
Example
let text = "Mr. Ben has a blue car";
let position = text.search("Ben");
console.log(position);
// logs 4
slice()
The slice()
method returns a new string containing a section of a string without altering the original string.
Syntax
str.slice(indexStart);
str.slice(indexStart, indexEnd);
Parameters
indexStart
This is the index of the first character to include in the returned substring.
indexEnd
This is the index of the first character to exclude in the returned substring.
Example
let str = "Welcome to Nigeria";
console.log(str.slice(11));
// expected result: "Nigeria"
console.log(str.slice(8, 11));
// expected result: "to"
split()
The split()
method creates an ordered list of substrings from a string. A string will be split into many parts
according to the seperator specified, and each element is returned as an array.
Syntax
str.split();
str.split(separator);
str.split(separator, limit);
Parameters
separator Optional
This pattern describes where each split should occur.
limit Optional
A non-negative integer specifying the maximum number of substrings to include in the array.
Example
let str = "Nigeria is an African country";
let words = str.split(" ");
console.log(words);
// expected result : [ 'Nigeria', 'is', 'an', 'African', 'country' ]
let chars = str.split("");
console.log(chars[0]);
// expected result "N"
let strCopy = str.split();
console.log(strCopy);
//expected result : [ 'Nigeria is an African country' ]
startsWith()
The startsWith()
method determines whether a string begins with the characters of a specified string, returning true or false.
Syntax
str.startsWith(searchString);
str.startsWith(searchString, position);
Parameters
searchString
The characters to be searched for at the beginning of this string. It cannot be a regex.
position Optional
A position at which searchString
should be found (the index of searchString
's first character). The default value is 0.
Example
const str1 = "Yesterday was my birthday";
console.log(str1.startsWith("Y"));
// expected output: true
console.log(str1.startsWith("Yes", 3));
// expected output: false
substring()
The substring()
method returns the part of the string between the start and end indexes or to the end.
Syntax
str.slice(indexStart);
str.slice(indexStart, indexEnd);
Parameters
indexStart
This index represents the first character in the returned substring.
indexEnd
This is the index of the first character to exclude in the returned substring.
Example
const str = "Breakfast";
console.log(str.substring(1, 3));
// expected output: "re"
console.log(str.substring(5));
// expected output: "fast"
toLocaleLowerCase()
It converts a string to lowercase letters according to the current locale.
Browser language settings determine the locale.
toLocaleLowerCase()
does not change the original string
Except for locales (such as Turkish) that conflict with regular Unicode case mappings, toLocaleLowerCase()
returns the same result as toLowerCase()
Syntax
str.toLocaleLowerCase();
str.toLocaleLowerCase(locales);
Parameters
locales optional
An array of strings containing BCP 47 language tags.
Example
let text = "Hello Nigeria!";
let result = text.toLocaleLowerCase();
console.log(result); // Expected: hello nigeria!
toLocaleUpperCase()
It converts a string to uppercase letters according to the current locale.
Browser language settings determine the locale.
toLocaleUpperCase()
does not change the original string
Except for locales (such as Turkish) that conflict with regular Unicode case mappings, toLocaleUpperCase()
returns the same result as toUpperCase()
Parameters
locales optional
An array of strings containing BCP 47 language tags.
Example
let text = "Hello Nigeria!";
let result = text.toLocaleUpperCase();
console.log(result); // Expected: HELLO NIGERIA!
toString()
toString
method returns a string as a string.
toString
method does not change the original string.
The toString
method converts a string object to a string.
Syntax
str.toString();
Example
let text = "Hello Nigeria!";
let result = text.toString();
console.log(result); // Hello Nigeria
trim()
The trim()
method removes the whitespace from both ends of a string and returns a new one.
Syntax
str.trim();
Example
const greeting = " Hello Nigeria! ";
console.log(greeting);
// expected output: " Hello Nigeria! ";
console.log(greeting.trim());
// expected output: "Hello Nigeria!";
valueOf()
The valueOf()
method returns a primitive value for a String.
Syntax
str.valueOf();
Example
let text = "Hello Nigeria!";
let result = text.valueOf();
console.log(result); // Hello Nigeria!
This concludes the list of commonly used methods in JavaScript. I hope you can use some of these for your projects.
Please, let me know what you think in the comment section.
Thanks for Reading 🌟🎉
I'd love to connect with you on Twitter
On to another blog, some other day, till then Femi👋.
Top comments (0)