Javascript String

In JavaScript, a string is a sequence of characters used to represent text. Strings are one of the fundamental data types in JavaScript and are commonly used to store and manipulate textual data.

String can be enclosed in Single Quotes like ‘john’ or Double Quotes like “john” or backtics (which came into ES6) like `john`.


var first_name ='John';
var last_name="Taylor";
var email=`john@abc.com`;

Note:- backtics is basically used to combined variable value and strings.

Example:- Now you add first_name and last_name along with Hello string.


var full_name=`Hello ${first_name} ${last_name}`;
console.log(full_name);  // Output:- John Taylor

Create a String:-

1) String():- You can create string through String function.


var age=35;
var age_string=String(age);  
console.log(age_string);  // Output:- "35"

var bool =true;
var bool_string=String(bool) // Output:- "true"

2) toString():- toString() is used to convert data into string.


var age =35;
var age_string=age.toString(); // Output "35";

var bool =true;
var bool_string=bool.toString() // Output:- "true"

3) creating a String Object through new keyword and it behaves like Object


var string_object = new String("John");
console.log(typeof string_object); //output:- "object" 

Concat two or more strings:- 1) You can concat the two string through + sign


var first_name="John";
var last_name="Taylor";
document.write(first_name + last_name); //Output:- JohnTaylor
document.write(first_name +' '+last_name); //Output:- John Taylor

Try it Yourself

2) You can concat strings through concat() keyword.


var first_name="John";
var last_name="Taylor";
document.write(first_name.concat(last_name)); //Output:- JohnTaylor

Try it Yourself

3) Concat string through backtics


var first_name="John";
var last_name="Taylor";
document.write(`${first_name} ${last_name}`); //Output:- John Taylor

Try it Yourself

trim() method:- this method is used to trim the white space from the string.


var name=" John ";
console.log(name.trim());  //Output:- John

split() method:- It is used to split a string into Array


var str="John went to college";
var str_arr=str.split(" ");
document.write(str_arr[0]);   // Output:- John
document.write(str_arr[1]);   // Output:- went
document.write(str_arr[2]);   // Output:- to
document.write(str_arr[3]);   // Output:- college

Try it Yourself

join() method:- It is used convert Array into String


arr=["John", "went", "to", "college"];
arr_to_string= arr.join("-");
document.write(arr_to_string);  // Output:- John-went-to-college

Try it Yourself

Reverse a string:-


var str="John Taylor"
let rev_string= str.split('').reverse().join('');
document.write(rev_string);  // Output:- rolyaT nhoJ

Try it Yourself