Enroll in Selenium Training

A string is a data type used in the programming languages which represents text. It includes a set of characters that can also contain spaces and numbers. For example, the word "hamburger" and the phrase "I ate three hamburgers" are both strings. Typically, programmers must enclose strings in quotation marks for the data to recognize as a string. In this article, we will discuss the details and usage of "String in JavaScript" covering across the following topics:

  • What are strings in JavaScript?
    • How to initialize Strings in JavaScript?
  • What inbuilt functions are provided by Strings in JavaScript?
  • Understanding String's Html wrapper methods?

What is a String in JavaScript?

Similar to other programming languages, the String is one of the data types in Javascript, which represent a sequence of characters. Still, in JavaScript, String can be both a primitive data type and a composite data type. In actual, the string in JavaScript is an object which lets you work with a series of characters and possesses the following characteristics:

  • A string represents any text inside a quote pair, and the quote pair can consist of either double or single quotes.
  • JavaScript doesn't impose any limit on the number of characters that a string can hold, but most of the old browsers support 255 characters only.
  • In addition to the above, JavaScript doesn't have a particular type that represents a single character of String. To represent a single character, we need to use a string of length 1.

Lets deep dive further to understand how to declare and use strings in JavaScript.

How to initialize String in JavaScript?

In JavaScript, we can initialize a String in the following two ways:

  • Using String literal
  • Using "new" Keyword

Let's discuss both of these ways in the sections below:

Initializing String using "String literal" method:

While creating a string object using the "string literal", the value of the String is assigned directly to the variable. We assign the value using the single quotes or double-quotes. Moreover, its syntax looks like below:

Syntax:

var variableName = ‘literal’; // Using single quotes

var variableName = "literal"; // Using double quotes

Let's try to understand the working of strings in JavaScript, when they initialize using string literals, using the following example:

<html>

   <body>  

      Demonstrating String initialization using literal in javascript

   </br>

      <script type = "text/javascript">

         var breakLine = "</br>";

         var var1 = 'Tools QA';

         document.write("Initialization using Single quotes: "+var1);

         document.write(breakLine);

         var1 = "Javascript Tutorials";

         document.write("Initialization using double quotes: "+var1);

         document.write(breakLine);

      </script>      

   </body>

</html>

Save the file with the name StringLiteral.html. After that, open it in any browser (Chrome, Firefox, or IE). It should show the output as: Using String in Javascript with Literals As is evident from the above screenshot, strings can be declared either using single or double-quotes. At line 7, the declaration & initialization of the variable "var1" happens using the single quotes, and then later at line 10, the same variable is re-initialized using double-quotes.

Initializing String using "new" Keyword:

Another way to initialize the String object is by using the "new" keyword, or we can say by using the constructor of the "String" class. Additionally, the parameters in the constructor can pass by using both single and double-quotes. Moreover, its syntax looks like below:

Syntax:

var variable = new String(‘literal’);

var variable = new String("literal");

Let's try to understand the working of strings in JavaScript, when they are initialized with the "new" keyword, using the following example:

<html>

   <body>  

      Demonstrating String initialization using new Keyword in javascript

   </br>

      <script type = "text/javascript">

         var breakLine = "</br>";

         var var1 = new String('Tools QA');

         document.write("Initialization using Single quotes: "+var1);

         document.write(breakLine);

         var1 = new String("Javascript Tutorials");

         document.write("Initialization using double quotes: "+var1);

         document.write(breakLine);

      </script>      

   </body>

</html>

Save the file with the name SingleNewKeyword.html. After that, open it in any browser (Chrome, Firefox, or IE). It should show the output as: Using string with new keyword In the above example, we declared the string object "var1" using the constructor of the String class and invoking the same with the "new" constructor. The constructor of the "String" object can accept both single and double-quoted character sequences.

What inbuilt functions are provided by Strings in JavaScript?

String supports many inbuilt functions in JavaScript. We are going to detail-out few of them in the below sections:

Length

This function returns the length of a provided string. Additionally, its syntax looks like below:

Syntax:

var data = new String(‘value’);
var len = data.length;

charAt

This function returns the character at the given index of the String. Also, its syntax looks like below:

Syntax:

var data = new String(‘value’);
var output = data.charAt(index);

charCodeAt

This function returns the Unicode value of character present at index. Moreover, its syntax looks like below:

Syntax:

var data = new String(‘value’);
var output = data.charCodeAt(index);

Concat

This function returns the combination of two or more strings. Its syntax looks like below:

Syntax:

var data1 = new String(‘value1’);
var data2 = new String(‘value2’);
var data3 = new String(‘value3’);
var data4 = new String(‘value4’);
.
.
.
var dataN = new String(‘valueN’);
var output = data1.concat(data2,data2,data3,data4,.....,dataN)

Match

This function returns the string that matches the provided pattern. Moreover, its syntax looks like below:

Syntax:

var data = new String(‘value1’);
var output = data.match(pattern);

indexOf

This function returns the starting index of the matching String in the provided input. Moreover, its syntax looks like below:

Syntax:

var data = new String(‘value1’);
var output = data.indexOf(SearchingData, fromIndex);

Where,

  • SearchingData:- A string that needs searching.
  • fromIndex:- Index from where the search needs to start. The default value is from the start of the String. This field is optional.

lastIndexOf

This function is similar to indexOf, except this returns the last occurrence index of the matching String. Additionally, its syntax looks like below:

Syntax:

var data = new String(‘value1’);
var output = data.lastIndexOf(SearchingData, fromIndex);

Where,

  • SearchingData:- A string that needs searching.
  • fromIndex:- Index from where value search needs to start. This field is optional.

Split

This function returns an array of Strings by splitting the given String into substrings based on the given separator. Moreover, its syntax looks like below:

Syntax:

var data = new String(‘value1’);
var output = data.split(separator, limit);

Where,

  • separator: based on which character or string data need to get split.
  • limit: Number of splits to be found. Moreover, this field is optional.

SubStr

This method returns the part of the String based on the given start and ends index value. Additionally, its syntax looks like below:

Syntax:

var data = new String(‘value1’);
var output = data.substr(startIndex, endIndex);

Where,

  • startIndex: The start index value from where substring needs to get started. Furthermore, it is an optional field; if not provided, then by default value will be 0.
  • endIndex: The end index value where substring needs to get ended.

toLowerCase

This function converts the given String into the lower case. Moreover, its syntax looks like below:

Syntax:

var data = new String(‘value1’);
var output = data.toLowerCase();

toUpperCase

This function converts the given String into the upper case. Moreover, its syntax looks like below:

Syntax:

var data = new String(‘value1’);
var output = data.toUpperCase();

toString

This function returns the String representing by the given object. It generally converts other object types to a string. Moreover, its syntax looks like below:

Syntax:

variable.toString();

valueOf

This function returns a primitive value of the provided object. Also, its syntax looks like below:

Syntax:

var data = new String(‘Primitive Value’);
data.valueOf();

As we have now understood the syntax of various inbuilt methods provided by the String class, let's create a simple example which uses all of the string as mentioned above functions and shows their usage:

<html>

   <body>  

      Demonstrating String inbuilt function in javascript

   </br>

      <script type = "text/javascript">

         var breakLine = "</br>";

         var var1 = new String('Tools QA tutorial for Javascript');

         document.write("Length of the input String is : "+var1.length);

         document.write(breakLine);

         document.write("Character At index 6 in provided string is: "+var1.charAt(6));

         document.write(breakLine);

         document.write("Character unicode At index 6 in provided string is: "+var1.charCodeAt(6));

         document.write(breakLine);

         document.write("Index value of character 'Q' in provided string is: "+var1.indexOf('Q'));

         document.write(breakLine);

         document.write("Last value of character 's' in provided string is: "+var1.lastIndexOf('s'));

         document.write(breakLine);

         var str2 = " for beginners";

         document.write("Concatenation of provided 2 strings are: "+var1.concat(str2));

         document.write(breakLine);

         document.write("Substring from index 0 to 8 strings are: "+var1.substr(0,8));

         document.write(breakLine);

         document.write("Converting provided string to lowercase: "+var1.toLowerCase());

         document.write(breakLine);

         document.write("Converting provided string to uppercase: "+var1.toUpperCase());

         document.write(breakLine);

         var value2 = 543.55;

         document.write("Converting number object to string: "+value2.toString());

         document.write(breakLine);

         var value3 = "9099";

         document.write("Converting String object to primitive: "+value3.valueOf());

         document.write(breakLine);

         document.write("Splitting String based on ' ' character: "+var1.split(' '));

         document.write(breakLine);

      </script>      

   </body>

</html>

Save the file with the name StringInBuiltFunction.html and open it in any browser (Chrome, Firefox, or IE). It should show the output as: Understanding inbuilt functions of strings in Javascript

What are String's Html wrapper methods?

The String class provides few "HTML wrapper methods", which returns the String wrapped inside the appropriate HTML tag. Let's discuss the syntax and usage of a few of these methods:

Big

This function wraps the given String with the <big> Html tag, which in turn going to change the font size of the given String in the Html. Moreover, its syntax looks like below:

Syntax:

var data = new String(‘value’);
data.big();

Blink

This function wraps the given String with the <blink> Html tag, which in turn going to blink the text in Html. Moreover, its syntax looks like below:

Syntax:

var data = new String(‘value’);
data.blink();

Anchor

This function wraps the given String with the <anchor> Html tag, which in turn going to create a hyperlink of the given String in Html. Additionally, its syntax looks like below:

Syntax:

var data = new String(‘value’);
data.anchor(nameAttribute);

Bold

This function wraps the given String with the <b> Html tag, which in turn going to change the text to bold in Html. Moreover, its syntax looks like below:

Syntax:

var data = new String(‘value’);
data.bold();

Fixed

This function wraps the given String with the <tt>Html tag, which in turn going to display text in a fixed-pitch font in Html. Additionally, its syntax looks like below:

Syntax:

var data = new String(‘value’);
data.fixed();

Italics

This function wraps the given String with the <i> Html tag, which in turn going to change the text into italics in Html. Moreover, its syntax looks like below:

Syntax:

var data = new String(‘value’);
data.italics();

Link

This function wraps the given String with the <a> Html tag, which in turn going to provide "href" for anchor tag in Html. Additionally, its syntax looks like below:

Syntax:

var data = new String(‘value’);
data.link("linkURL");

Strike

This function wraps the given String with the <strike> Html tag, which in turn going to strike the given text in Html. Moreover, its syntax looks like below:

Syntax:

var data = new String(‘value’);
data.strike();

Small

This function wraps the given String with the <small> Html tag, which in turn going to display text in small font in Html. Additionally, its syntax looks like below:

Syntax:

var data = new String(‘value’);
data.small();

Sub

This function wraps the given String with the <sub> Html tag, which in turn going to display subscript of the given text in Html. Moreover, its syntax looks like below:

Syntax:

var data = new String(‘value’);
data.sub();

Sup

This function wraps the given String with the <sup> Html tag, which in turn going to display superscript of the given text in Html. Also, its syntax looks like below:

Syntax:

var data = new String(‘value’);
data.sup();

Fontsize

This function wraps the given String with the <font size= "size"> Html tag, which in turn going to display text in the mentioned size in Html. Moreover, its syntax looks like below:

Syntax:

var data = new String(‘value’);
data.fontsize(size);

As we have now understood the syntax of various HTML wrapper methods provided by the String class, let's create a simple example which uses all of the string as mentioned above functions and shows their usage:

<html>

	<body> 
		Demonstrating String HTML Wrapper functions in javascript </br>
    	<script type="text/javascript">
		    var breakLine = "</br>";
		    var var1 = new String('Tools QA tutorial for Javascript');
		    document.write("Big function of the input String is : " + var1.big());
		    document.write(breakLine);
		    document.write("Blink function of the input String is : " + var1.blink());
		    document.write(breakLine);
		    document.write("Anchor function of the input String is : " + var1.anchor("Anchor"));
		    document.write(breakLine);
		    document.write("Bold function of the input String is : " + var1.bold());
		    document.write(breakLine);
		    document.write("Fixed function of the input String is : " + var1.fixed());
		    document.write(breakLine);
		    document.write("Italics function of the input String is : " + var1.italics());
		    document.write(breakLine);
		    document.write("Link function of the input String is : " + var1.link("www.toolsQA.com"));
		    document.write(breakLine);
		    document.write("Strike function of the input String is : " + var1.strike());
		    document.write(breakLine);
		    document.write("Small function of the input String is : " + var1.small());
		    document.write(breakLine);
		    document.write("Subscript function of the input String is : " + var1.sub());
		    document.write(breakLine);
		    document.write("SuperScript function of the input String is : " + var1.sup());
		    document.write(breakLine);
		    document.write("Font function of the input String is : " + var1.fontsize('5'));
		    document.write(breakLine);    
    	</script>
	</body>

</html>

Save the file with name htmlWrappers.html. After that, open it in any browser (Chrome, Firefox, or IE). It should show the output as: Understanding HTML Wrapper Functions of JS String As we can see from the above screenshot that, all these methods change the HTML characteristics/attributes of the variables. Moreover, the output on the right-hand side of the screenshot validates the same.

Key Takeaways

  • String in JavaScript is an object which represents a sequence of characters.
  • Moreover, Strings in JavaScript can represent both using single or double-quotes.
  • Additionally, they provide multiple inbuilt functions such as length(), charAt(), concat(), split() etc, which makes the string manipulation very easy.
  • Strings also provide some HTML wrapper methods such as Big(), Small(), Blink(), Link(), etc. using which the HTML properties can alter for a string.

To conclude, let's now move to the next article to understand how JavaScript makes mathematical calculations very easy using the "Math class in JavaScript."

Callback functions in JavaScript
Callback functions in JavaScript
Previous Article
Math Object in JavaScript
Math Object in JavaScript
Next Article

Similar Articles

Feedback