Strings are a sequence of characters in javascript. You can create a string using single, double or using string()
.
Example
var sentence_one = "Very nice to see you";
var sentence_two = 'Good to see you';
console.log(sentence_one);
console.log(sentence_two);
//Console Output
Very nice to see you
Good to see you
Creating string using String()
Class.
var desc = new String("It was a wonderful day.");
console.log(desc.toString());
//Console Output
It was a wonderful day.
We'll not be using this example in our tutorial so stick with first example.
Get string length
Every string has the property length
which returns the count of characters including empty spaces.
x = "Hello World";
y = "HelloWorld";
console.log(x.length);
console.log(y.length);
//Console Output
11
10
Escape special character from string
Special Character Example
var string = "Welcome to pink city "Jaipur"";
As you can see that double quotes beside Jaipur are used for giving importance or highlighting. If we display the above string we'll receive Uncaught SyntaxError: Unexpected identifier
the error in console. This is because the browser will consider both as same. We can solve this by replacing double quotes to single quotes.
var string = "Welcome to pink city 'Jaipur'";
console.log(string);
//Console Output
Welcome to pink city 'Jaipur'
Or else we can use a backslash /
to escape double-quotes.
var string = "Welcome to pink city "Jaipur"";
console.log(string);
//Console Output
Welcome to pink city "Jaipur"
The first and second backslash will be before double-quotes.
var string = 'Welcome to pink city 'Jaipur'';
console.log(string);
//Console Output
Welcome to pink city 'Jaipur'
Concatenation of string
Concatenation means joining or appending two or more strings into a single string. To concatenate strings we use +
operator. It is to be noted by +
is also an addition operator.
var name = "Chetan";
var age = 12;
var string = name+" will be "+age+" years old on this years birth day";
console.log(string);
//Console Output
Chetan will be 12 years old on this years birth day
You can append strings and also numbers.
Split string in parts
split()
a method is used to cut the string in parts this function returns an array of strings.
Syntax
str.split(separator,limit)
var names = "suresh, ramesh, vijay, kiran";
console.log(names.split(","));
//Console Output
(4) ["suresh", " ramesh", " vijay", " kiran"]
console.log(names.split(",", 2));
//Console Output
(2) ["suresh", " ramesh"]
Replace string
This method replaces specified words or any other characters of the string and returns replaced string.
Syntax
str.replace(search_value,replace_value);
Example
var names = "suresh, ramesh, vijay, kiran";
console.log(names.replace("vijay", "pavan"));
//Console Output
suresh, ramesh, pavan, kiran
You can see that the name "vijay" got replaced with "pavan".It does not modify the original string.
I’ve included a whole chapter on Javascript Strings
Top comments (0)