Javascript String

String is one of the most basic primitive data types of javascript which holds data in text format.

String in javascript are little different from the strings in other programming language and has different ways of declaring them.

We can use single quotes '', double quotes "" or back ticks`` to declare string in Javascript.

Syntax:

'Hello World!';
"Hello World!";
`Hello World!`;

The single quotes '' and double quotes "" strings function similarly and has some limitations, but back ticks `` also know as Template literals which are introduced in ES6 solves much of the issues.

A string can also be declared using String(data) global object. This object converts any thing to string.

console.log(String(25));
//"25"

console.log(String(null));
//"null"

console.log(String(NAN));
//"NaN"

console.log(String(Number));
//"function Number() { [native code] }"

Difference between primitive string and String(data) object

Javascript differentiates the strings declared with different methods. String created as a constructor using new String(data) returns an object and String created without new keyword are primitive strings.

let str1 = new String(25);
let str2 = String(25);

console.log(typeof str1);
//object

console.log(typeof str2);
//string

JavaScript automatically converts primitives to String objects, so that it’s possible to use String object methods for primitive strings.


Single and double quotes string

When we declare string using '' or "" quotes we get a setback when try to add those characters inside the string.

console.log('I am 'Prashant Yadav'');
console.log("I am "Prashant Yadav"");

//Uncaught SyntaxError: missing ) after argument list

This won’t work as expected because when we try to re declare the same single or double quotes inside the string it represents that we are terminating the string.

We can solve this issue by either using single quotes with double quotes or vice versa or escape the characters.

console.log('I am "Prashant Yadav"');
//I am "Prashant Yadav"

console.log("I am 'Prashant Yadav'");
//I am 'Prashant Yadav'

console.log("I am \"Prashant Yadav\"");
//I am "Prashant Yadav"

\" escapes / allows us to use the double quote characters in the string.

Similarly, if you want to print the string in multiple lines then we need to escape the string with \n which will print the following string on next line.

console.log('I am Prashant Yadav,
How are you?');
//Uncaught SyntaxError: Invalid or unexpected token

console.log('I am Prashant Yadav, \n How are you?');
/*
I am Prashant Yadav, 
 How are you?
*/

Following are the list of escape characters in javascript

Code Result
\XXX To insert an octal Latin-1 character.
\’ To insert single Quote.
\” To insert double Quote.
\\ To insert backslash
\n To insert new line
\r To insert carriage return
\v To insert vertical tab
\t To insert a tab
\b To insert a backspace
\f To insert form feed
\uXXXX To insert unicode codepoint
\xXX To insert the Latin-1 character

Alternatively, we can use Template literals `` which will solve all the above problems.

console.log(`I am "Prashant Yadav"`);
//I am "Prashant Yadav"

console.log(`I am 'Prashant Yadav'`);
//I am 'Prashant Yadav'

let str =  `I am Prashant Yadav,
 How are you?`;

console.log(str);
/*
I am Prashant Yadav,
 How are you?
*/

Characters in javascript

Javascript does not have different data type for characters, Just declare a string with single character to represent the characters.

let char = 'a';

Strings are an array like object in javascript and we can use this advantage to access characters in the string.

let str = 'learnersbucket';
console.log(str[5]);
//'e'

It is zero indexes based just like an array. However, we can use this method just to access the characters, Deleting and Changing the character won’t work. Checkout Object.defineProperty() for more details.

We can also use charAt() method as well which returns the character at the given index.

let str = 'learnersbucket';
console.log(str.charAt(5));
//'e'

String.prototype.length method can be used to get the length of the string.

let str = 'learnersbucket';
console.log(str.length);
//14

Print each character of string

As strings are array like object we can loop through them to print all the characters.

let str = 'javascript';
for(let i = 0; i < str.length; i++){
  console.log(str[i]);
}
//j
//a
//v
//a
//s
//c
//r
//i
//p
//t

We can also use for of loop to print the characters.

let str = 'javascript';
for(let char of str){
  console.log(char);
}
//j
//a
//v
//a
//s
//c
//r
//i
//p
//t

Passing dynamic data to string in javascript

Strings are immutable data structures which means once created we cannot modify it however we can glue or join two or more strings to create a new string. + operator is used to concatenate two strings.

let str1 = 'Prashant';
let str2 = 'Yadav';

console.log(str1 + " " + str2);
//Prashant Yadav

String.prototype.concat() can also be used to concatenate two strings.

We can pass the dynamic data as well by concatenating it with string.

Dynamic data in usual string

let name = 'Prashant Yadav';
console.log("My name is " + name);
//My name is Prashant Yadav

console.log("My name is " + name + " and I am a software engineer");
//My name is Prashant Yadav and I am a software engineer

We can also pass data dynamically in template strings.

let name = 'Prashant Yadav';
console.log(`My name is ${name}`);
//My name is Prashant Yadav

console.log(`2 * 2 = ${2 * 2}`);
//2 * 2 = 4

${} is a special syntax through which we can pass data inside the string using Template literals.

A complete list of string methods in javascript.

Following is the list of different operations which we can perform on the string.

Leave a Reply

Your email address will not be published. Required fields are marked *