In this article, we have shared some of the useful JavaScript string methods. These methods can help you in manipulating strings and data structures. You will find these methods useful in various programming tasks.
charAt()
The JavaScript charAt() method returns a new string consisting of the single UTF-16 code unit located at the specified offset into the string. This function can be used to determine whether a particular character is present in a string.
"w3tweaks.com".charAt(3);
// Output: w
concat()
The JavaScript concat() method is used to join the string arguments together. It returns a new string that contains the combined results of the previous calls to the two arguments.
"w3".concat("", "tweaks.com");
// Output: w3tweaks.com
startsWith()
The Javascript startsWith method returns true if the string begins with the specified characters, and false otherwise. This method is case-sensitive, meaning that uppercase and lowercase characters are treated as different characters. The startsWith method can be used with arrays, like String, or with other objects that have a length property and index access.
"w3tweaks.com".startsWith("w");
// Output: true
"w3tweaks.com".startsWith("3");
// Output: false
endsWith()
The endsWith() method determines whether a string ends with the characters of another string, returning true or false as appropriate.
"w3tweaks.com".endsWith("m");
// Output: true
"w3tweaks.com".startsWith("M");
// Output: false
includes()
The Javascript string method includes() determines whether a string contains the given substring. It returns true or false depending on the result. This method is case-sensitive, meaning that upper and lowercase letters are considered to be different characters. The include() method is part of the ECMAScript 2015 standard and is supported in all modern browsers.
"w3tweaks.com".includes("t");
// Output: true
"w3tweaks.com".includes("M");
// Output: false
indexOf()
The indexOf() method is used to find the index of the first occurrence of a specified value in a string. This method returns -1 if the value to search for is not present in the string.
"w3tweaks.com".includes("t");
// Output: 2
"w3tweaks.com".indexOf("M");
// Output: -1
lastIndexOf()
The lastIndexOf() method is used to find the last occurrence of a specified value in a string. This method returns the index of the last occurrence of the specified value, or -1 if the value is not found. If the specified value is not a string, then it is converted to a string before searching for it.
"w3tweaks.com".lastIndexOf("w");
// Output: 3
"w3tweaks.com".indexOf("W");
// Output: -1
match()
The match() method searches a string for a match against a regular expression, and returns the matches, as an Array object.
"W3tweaks.Com".match(/[A-Z]/g);
// Output: ["W","C"]
"w3tweaks.com".match(/[A-Z]/g);
// Output: null
matchAll()
The matchAll() method returns an iterator over all results matching a string against a regular expression, including capturing groups.
const regexp = /t(e)(st(\d?))/g;
const str = 'test1test2';
const array = [...str.matchAll(regexp)];
console.log(array[0]);
// expected output: Array ["test1", "e", "st1", "1"]
console.log(array[1]);
// expected output: Array ["test2", "e", "st2", "2"]
padStart()
The padStart() method pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start of the current string.
"w3tweaks.com".padStart(16, "www.");
// Output: 'www.w3tweaks.com'
padEnd()
The padEnd() method pads the current string with a given target length from the end of the string. The padding is applied from the start of the string if it is not long enough.
"www.w3tweaks".padEnd(16, ".com");
// Output: 'www.w3tweaks.com'
repeat()
The repeat() method is used to create a new string with a specified number of copies of an existing string.
"www.w3tweaks".repeat(2);
// Output: 'www.w3tweaks.comwww.w3tweaks.com'
replace()
The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. If you specify a function as the replacement, it will be called with matched groups from the pattern as arguments.
"www.w3tweaks.com".replace("www.","https://www.");
// Output: 'https://www.w3tweaks.com'
search()
The search() method searches a string for a specified value and returns the position of the match. The search value can be a string or a regular expression. This method returns -1 if no match is found.
"www.w3tweaks.com".search("w3");
// Output: 4
"www.w3tweaks.com".search("w33");
// Output: -1
slice()
The JavaScript slice() string method is used to extract a part of a string and return it as a new string. This method is often used to extract substrings. The syntax for the slice() method is: str.slice(beginIndex, endIndex). The beginIndex parameter is the index where the extraction will start and the endIndex parameter is the index where the extraction will end (but not including the character at that index). If either of these parameters is omitted, then their default values are 0 and str.length respectively.
"www.w3tweaks.com".slice(4,16);
// Output: 'w3tweaks.com'
split()
The JavaScript split() method is used to split a string into an array of substrings and returns the new array. The original string is not modified. This method is often used to extract parts of a string that match a regular expression or to extract portions of a string delimited by certain characters.
"w3tweaks".split("");
// Output: ['w', '3', 't', 'w', 'e', 'a', 'k', 's']
substring()
The JavaScript substring() string method extracts the characters from a string between two specified indices and returns the new substring. This method has two forms: substring(begin) and substring(begin, end). The first form extracts the characters in a string from the beginning to the end of the string. The second form lets you specify which part of the string you want to extract.
"www.w3tweaks.com".substring(4,16);
// Output: 'w3tweaks.com'
toLowerCase()
The JavaScript toLowerCase() method returns the string converted to lowercase. This method does not affect the value of the string itself since JavaScript strings are immutable. The toLowerCase() method is used in many places where you need to normalize data, such as when comparing two strings.
"W3TWEAKS.COM".toLowerCase();
// Output: 'w3tweaks.com'
toUpperCase()
The JavaScript toUpperCase() method is used in JavaScript to convert the characters within a string to uppercase letters. The method does not change the original string, it simply returns a new one with the altered content. This function can be very useful when working with strings that are all in lowercase, or mixed case.
"w3tweaks.com".toUpperCase();
// Output: 'W3TWEAKS.COM'
trim()
The JavaScript trim() string method in JavaScript is used to remove whitespace from the beginning and end of a string. Whitespace in this context includes any characters that produce a space character when rendered, including tabs and newlines. The trim() method does not change the contents of the string but merely returns a new string with the whitespace removed from the start and end.
" w3tweaks.com ".trim();
// Output: 'w3tweaks.com'
trimStart()
The trimStart() method removes whitespace from the beginning of a string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).
" w3tweaks.com ".trimStart();
// Output: 'w3tweaks.com '
trimEnd()
The trimEnd() method removes whitespace from the end of a string. This method does not change the original string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).
" w3tweaks.com ".trimEnd();
// Output: ' w3tweaks.com'
codePointAt()
The JavaScript codePointAt() method returns a Unicode code point value. It is used in string manipulation. The method takes an index as an argument and returns the code point at that index. If you’re not familiar with Unicode, it’s a standard that defines a set of characters that are used in written languages around the world.
"w3tweaks.com".codePointAt();
// Output: 119
fromCodePoint()
The fromCodePoint() method is used to create a string from the given code points. This method follows the ECMAScript 6 standard.
String.fromCodePoint(119, 51, 116, 119, 101,97,107,115);
// Output:'w3tweaks'
localeCompare()
The localeCompare() method is used to compare two strings in the current locale. The standard sort order is based on the Unicode character value. In simple terms, this method returns a Number that indicates how the given string compares to the reference string.
const a = 'réservé'; // with accents, lowercase
const b = 'RESERVE'; // no accents, uppercase
console.log(a.localeCompare(b));
// expected output: 1
console.log(a.localeCompare(b, 'en', { sensitivity: 'base' }));
// expected output: 0
Leave a Reply