Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
Characters or sequences of characters in JavaScript are stored as strings. Strings are either used to represent or manipulate data in JavaScript. A JavaScript string can have either 0 or more characters within the quotes. There are three kinds of quotes for strings, various special characters to use within those quotes and several functions to manipulate, operate on, or retrieve strings or substrings. This article will discuss the common operations on strings, along with illustrative and suitable examples.
This shows that we cannot alter the string once it is generated. To do so, we must create a new string and concatenate the previous one onto it as shown below.
let str = 'Name';
str = 'n' + str[1]; // replacing the old string with the new one
alert( str ); // name
You can also try this code with Online Javascript Compiler
There is no effective difference between single and double quotes, but it is recommended that we stick to using one of them throughout the code to enhance the readability. However, there is a new way of writing strings: template literals.
let backticks=`Hello`
You can also try this code with Online Javascript Compiler
Template literals use backticks to easily build dynamic strings. Backticks are much more versatile than both single and double-quotes. They allow multiline strings and also embed expressions into the string (by wrapping in ${…}.
For example:
Multline strings:
let employees= `Employee:
* Ryan
* Chris
* Anne
`;
alert(employees);
// multiline strings
You can also try this code with Online Javascript Compiler
The .length property is often confused with the length() method which is used in many programming languages. But it is worth noting that both are distinct in nature.
Now let us see how one can access the characters of a string:
Accessing characters
To get a character at a particular position, we can either specify it using square brackets [position] or by calling the method string.charAt(position). The first position is always zero. Therefore, the last character is one less than the length.
let str1 = `Name`;
alert( str1[0] ); // the first character is N
alert( str1.charAt(0) ); //the first character is N
alert( str1[str1.length - 1] ); //the last character is e
You can also try this code with Online Javascript Compiler
Substrings are sub-parts within the given string, either a fragment of the string or the complete string itself. To attain substrings, we can use slice, substring or substr.
Let us look at them one by one:
slice
It is written as string.slice(start, end), where start is the starting index and the second argument(specifying the end) is optional.
If the end is mentioned too, slice returns the substring from the given starting index until before the end(not the end).
For examples:
let str = "Paris"; alert( str.slice(0, 4) ); // returns 'Pari' starting from 0, excluding 4
If the starting and ending positions are interchanged, the slice returns an empty string. However, unlike slice, substring does not support negative arguments and treats them as 0.
substr
It is pretty similar to string.slice(start, length), only one change has to perform that instead of specifying the end position, users need to specify the substring length. Substr accepts negative values for start argument, while the length always has to be positive.
let str = "Hamilton";
alert( str.substr(0, 3) ); // 'Ham', 3 characters starting from the 1st position
alert( str.substr(-6, 4) ); // 'mil', 4 characters starting from the 6th position backwards
You can also try this code with Online Javascript Compiler
This searches within the string for the given substring starting from a given position. It will either return the position where the match is found or return -1 if it isn’t found.
It is case sensitive, and the syntax for this is str.indexOf(substring). We can also have an optional position parameter like: str.indexOf(substring, position).
letstr = 'Chris from Paris'; alert( str.indexOf('Chris') ); // the position returned will be 0
alert( str.indexOf('Paris') ); // the position returned will be 11
alert( str.indexOf('Par') ); // the position returned will be 11
alert( str.indexOf('is') ); // the position returned will be 3 because that's the first occurrence of the given substring alert( str.indexOf('london') ); // returns -1, as it is case-sensitive
alert( str.indexOf('is', 4) ); // the first occurrence of 'is' is 3. Therefore we'll start searching from index 4. Returns 14.
bitwise NOT trick
This converts numbers to 32 digit integers, removing their decimal parts, and reverses all bits in binary representation.~n equals -(n+1).
~2 returns -3, which is equal to -(2+1)
~0 returns -1, which is equal to -(0+1)
~-1 returns 0, which is equal to -(-1+1)
Therefore, ~n zero only for n == -1 (for 32-bit signed integer n).
Now, if (~str.indexOf(...)) reads as “if found”, and to shorten indexOf checks:
let str = "Paris";
if (~str.indexOf("Paris"))
{
alert( 'Found it!' ); // works
}
You can also try this code with Online Javascript Compiler
Moving on to the more efficient and modern way for the same purpose:
includes, startsWith, endsWith
All three of these functions return true or false for the substring being found in the given string. We could just use .includes(string), or specify the position to start searching from as in .includes(string, position).
alert( "Chris in Paris".includes("Chris") ); // returns true
alert( "Chris in Paris".includes("chris") ); // returns false because it is case sensitive
alert( "Chris in Paris".includes("Chris", 7) ); // returns false because there is no “Chris” after position 7
.startsWith(string) and .endsWith(string) are the syntaxes for functions that check the beginning and end of a string for the substring, respectively.
alert( "Chris in Paris".startsWith("Chr") ); // returns true
alert( "Chris".endsWith("is") ); // returns true
You can also try this code with Online Javascript Compiler
The following are some important points we must remember for comparison between strings:
There is a character-by-character comparison between two strings.
Lowercase strings are greater than uppercase strings.
Diacritical marks on characters (á, é, ó, ü, ñ) in strings often cause unexpected results.
Both upper and lower-case characters in strings have specific numeric codes or ASCII codes. (Starting from 065 for uppercase alphabets and 097 for lowercase alphabets. Therefore a>A, h>H, etc)
alert( 'c' > 'G' ); // returns true
You can also try this code with Online Javascript Compiler
This takes the position as string.codePointAt(position), and returns the ASCII code for the character at the given position:
alert( "apple".codePointAt(0) ); // returns 97 because lowercase a has code 97
alert( "Apple".codePointAt(0) ); // returns 65 because uppercase A has code 65
You can also try this code with Online Javascript Compiler
Special characters, always known as escape characters and escape sequences always begin with a backslash'/'. Escape sequences are character sequences inserted in a string to have a meaning different from the literal characters.
Some common special characters in JavaScript include:
\n
Newline
\', \"
Quotes
\\
Backslash
\t
Tab
\b, \f, \v
Backspace, Form Feed, Vertical Tab – kept for compatibility, not used nowadays.
\r
Carriage return
We can create multiline strings even without backticks, with single and double quotes by using the newline character-\n, denoting a line break:
let string1 = "Chris\nAnne"; // two lines using a "newline symbol"
let string2= `Chris
Anne`;
alert(string1 == string2); // true
You can also try this code with Online Javascript Compiler
Q1. How can we remove leading and trailing spaces in a string?
Ans. The .trim() method helps us remove extra spaces both at the beginning and the end of a string in JavaScript.
Q2. What are the three methods of getting substrings from Js Strings?
Ans. We can use either of the three: .slice(start,end), .substring(start,end) or substr(start, length) to get case-sensitive substrings in JavaScript.
Q3. How can we join two or more strings in JavaScript?
Ans. The .concat() method helps join two or more strings. The syntax for this method can be: str1.concat(" ", str2)
letstring1 = "Hey"; letstring2 = "students!"; letstring3 = "Great to see you!"; letresult = string1.concat(" ", string2, " ", string3);
Q4. What is the repeat method used in Javascript?
Ans. The .repeat() method repeats the string n number of times. Its syntax is str.repeat(n) – where ‘str’ is the string and ‘n’ is the number of times a user wants the string repeated.
Key takeaways
In this article, we learned about the operations we can perform on strings includes searching and retrieving substrings, comparing two strings and many more. We have extensively used examples to illustrates the concept and better clarification the situations where each kind of method could be applied.
You can go to Coding Ninjas Studio to try and solve more problems for practice. Share this blog with your friends if you found it helpful! Until then, All the best for your future endeavours, and Keep Coding.