Teachnique
      CourseRoadmaps
      Login

      OverviewPlacementSyntaxHello WorldConsole.log()CommentsVariableslet StatementConstantsData TypesType ConversionsStrict ModeReserved Keywords

      OperatorsArithmetic OperatorsComparison OperatorsLogical OperatorsBitwise OperatorsAssignment OperatorsConditional Operatorstypeof OperatorNullish Coalescing OperatorDelete OperatorComma OperatorGrouping OperatorYield OperatorSpread OperatorExponentiation OperatorOperator Precedence

      If...ElseWhile LoopsFor LoopFor...in LoopFor...of LoopLoop ControlBreak StatementContinue StatementSwitch CaseUser Defined Iterators

      FunctionsFunction ExpressionsFunction ParametersDefault ParametersFunction() ConstructorFunction HoistingArrow FunctionsFunction InvocationFunction call() MethodFunction apply() MethodFunction bind() MethodClosuresVariable ScopeGlobal VariablesSmart Function Parameters

      NumberBooleanStringsArraysDateMathRegExpSymbolSetsWeakSetMapsWeakMapIterablesReflectTypedArrayTempate LiteralsTagged Templates

      Objects OverviewClassesObject PropertiesObject MethodsStatic MethodsDisplay ObjectsObject AccessorsObject ConstructorsNative PrototypesES5 Object MethodsEncapsulationInheritanceAbstractionPolymorphismDestructuring AssignmentObject DestructuringArray DestructuringNested DestructuringOptional ChainingGlobal ObjectMixinsProxies

      HistoryVersionsES5ES6ECMAScript 2016ECMAScript 2017ECMAScript 2018ECMAScript 2019ECMAScript 2020ECMAScript 2021ECMAScript 2022

      CookiesCookie AttributesDeleting Cookies

      Browser Object ModelWindow ObjectDocument ObjectScreen ObjectHistory ObjectNavigator ObjectLocation ObjectConsole Object

      Web APIHistory APIStorage APIForms APIWorker APIFetch APIGeolocation API

      EventsDOM Events

      Feedback

      Submit request if you have any questions.

      Course
      Strings

      JavaScript Tutorial

      This JavaScript tutorial is crafted for beginners to introduce them to the basics and advanced concepts of JavaScript. By the end of this guide, you'll reach a proficiency level that sets the stage for further growth. Aimed at empowering you to progress towards becoming a world-class software developer, this tutorial paves the way for a successful career in web development and beyond.

      Strings Object

      The String object in JavaScript lets you work with a series of characters; it wraps JavaScript's string primitive data type with a number of helper methods.
      As JavaScript automatically converts between string primitives and String objects, you can call any of the helper methods of the String object on a string primitive.
      The string is a sequence of characters containing 0 or more characters. For example, 'Hello' is a string.

      Syntax

      JavaScript strings can be created as objects using the String() constructor or as primitives using string literals.
      Use the following syntax to create a String object
      const val = new String(value);
      The String parameter, value is a series of characters that has been properly encoded.
      We can create string primitives using string literals and the String() function as follows −
      str1 = 'Hello World!'; // using single quote
      str2 = "Hello World!"; // using double quote
      str3 = 'Hello World'; // using back ticks
      str4 = String('Hello World!'); // using String() function

      String Properties

      Here is a list of the properties of String object and their description.
      Sr.No.
      Property & Description
      1
      AI
      Returns a reference to the String function that created the object.
      2
      AI
      Returns the length of the string.
      3
      AI
      The prototype property allows you to add properties and methods to an object.

      String Methods

      Here is a list of the methods available in String object along with their description.

      Static Methods

      The static methods are invoked using the 'String' class itself.
      Sr.No.
      Property & Description
      1
      AI
      Converts the sequence of UTF-16 code units into the string.
      2
      AI
      Creates a string from the given sequence of ASCII values.

      Instance Methods

      The instance methods are invoked using the instance of the String class.
      Sr.No.
      Method & Description
      1
      AI
      Returns the character from the specified index.
      2
      AI
      Returns the character at the specified index.
      3
      AI
      Returns a number indicating the Unicode value of the character at the given index.
      4
      AI
      Returns a number indicating the Unicode value of the character at the given index.
      5
      AI
      Combines the text of two strings and returns a new string.
      6
      AI
      Checks whether the string ends with a specific character or substring.
      7
      AI
      To check whether one string exists in another string.
      8
      AI
      Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found.
      9
      AI
      Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found.
      10
      AI
      Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.
      11
      AI
      Used to match a regular expression against a string.
      12
      AI
      Used to match all occurrences of regular expression patterns in the string.
      13
      AI
      To get the Unicode normalization of the string.
      14
      AI
      To add padding to the current string with different strings at the end.
      15
      AI
      To add padding to the current string with different strings at the start.
      16
      AI
      Used to find a match between a regular expression and a string and replace the matched substring with a new one.
      17
      AI
      Used to find a match between a regular expression and a string and replace all the matched substring with a new one.
      18
      AI
      To get a new string containing the N number of copies of the current string.
      19
      AI
      Executes the search for a match between a regular expression and a specified string.
      20
      AI
      Extracts a section of a string and returns a new string.
      21
      AI
      Splits a String object into an array of strings by separating the string into substrings.
      22
      AI
      Returns the characters in a string beginning at the specified location through the specified number of characters.
      23
      AI
      Returns the characters in a string between two indexes into the string.
      24
      AI
      The characters within a string are converted to lowercase while respecting the current locale.
      25
      AI
      The characters within a string are converted to the upper case while respecting the current locale.
      26
      AI
      Returns the calling string value converted to lowercase.
      27
      AI
      Returns a string representing the specified object.
      28
      AI
      Returns the calling string value converted to uppercase.
      29
      AI
      It removes white spaces from both ends.
      30
      AI
      It removes white spaces from the start.
      31
      AI
      It removes white spaces from the end.
      32
      AI
      Returns the primitive value of the specified object.

      Example: Creating JavaScript String Objects

      In the example below, we used the string() constructor with the 'new' keyword to create a string object.
      <html>
      <head>
      <title> JavaScript - String Object </title>
      </head>
      <body>
      <p id = "output"> </p>
      <script>
      const str = new String("Hello World!");
      document.getElementById("output").innerHTML =
      "str == " + str + "<br>" +
      "typeof str == " + typeof str;
      </script>
      </body>
      </html>

      Output

      str == Hello World!
      typeof str == object

      Accessing a String

      You can access the string characters using its index. The string index starts from 0.

      Example

      In the example below, we access the character from the 0th and 4th index of the string.
      <html>
      <head>
      <title> JavaScript - Accessing a string </title>
      </head>
      <body>
      <p id = "output"> </p>
      <script>
      const str1 = new String("Welcome!");
      let str2 = "Welcome!";
      document.getElementById("output").innerHTML =
      "0th character is - " + str1[0] + "<br>" +
      "4th character is - " + str2[4];
      </script>
      </body>
      </html>
      Output
      0th character is - W
      4th character is - o

      JavaScript Strings are Case-sensitive

      In JavaScript, strings are case-sensitive. It means lowercase and uppercase characters are different.

      Example

      In the example below, char1 contains the uppercase 'S', and char2 contains the lowercase 's' characters. When you compare char1 and char2, it returns false as strings are case-sensitive.
      <html>
      <head>
      <title> JavaScript - String case-sensitivity </title>
      </head>
      <body>
      <p id = "output">
      <script>
      let char1 = 'S';
      let char2 = 's'
      let ans = char1 == char2;
      document.getElementById("output").innerHTML += "s == S " + ans;
      </script>
      </body>
      </html>
      Output
      s == S false

      JavaScript Strings are Immutable

      In JavaScript, you can't change the characters of the string. However, you can update the whole string.

      Example

      In the example below, we try to update the first character of the string, but it doesn't get updated, which you can see in the output.
      After that, we update the whole string, and you can observe the changes in the string.
      <html>
      <head>
      <title> JavaScript − Immutable String </title>
      </head>
      <body>
      <p id = "output"> </p>
      <script>
      const output = document.getElementById("output");
      let str = "Animal";
      str[0] = 'j';
      output.innerHTML += "The string is: " + str + "<br>";
      str = "Hi!";
      output.innerHTML += "The updated string is: " + str;
      </script>
      </body>
      </html>
      Output
      The string is: Animal
      The updated string is: Hi!

      Escape Characters

      You can use the special characters with the string using the backslash (\) characters. Here is the list of special characters.
      Escape character
      Description
      \"
      Double quote
      \'
      Single quote
      \\
      Backslash
      \n
      New line
      \t
      Tab
      \b
      backspace
      \f
      Form feed
      \v
      Verticle tab
      \r
      Carriage return
      \uXXXX
      Unicode escape

      Example

      In the example below, we added a single quote between the characters of the str1 string and a backslash between the characters of the str2 string.
      <html>
      <head>
      <title> JavaScript - Escape Characters </title>
      </head>
      <body>
      <p id = "output"> </p>
      <script>
      const output = document.getElementById("output");
      let str1 = "Your\'s welcome!";
      let str2 = "Backslash \\";
      output.innerHTML += "str1 == " + str1 + "<br>";
      output.innerHTML += "str2 == " + str2 + "<br>";
      </script>
      </body>
      </html>
      Output
      str1 == Your's welcome!
      str2 == Backslash \

      String HTML Wrappers

      Here is a list of the methods that return a copy of the string wrapped inside an appropriate HTML tag.
      Sr.No.
      Method & Description
      1
      AI
      Creates an HTML anchor that is used as a hypertext target.
      2
      AI
      Creates a string to be displayed in a big font as if it were in a <big> tag.
      3
      AI
      Creates a string to blink as if it were in a <blink> tag.
      4
      AI
      Creates a string to be displayed as bold as if it were in a <b> tag.
      5
      AI
      Causes a string to be displayed in fixed-pitch font as if it were in a <tt> tag
      6
      AI
      Causes a string to be displayed in the specified color as if it were in a <font color="color"> tag.
      7
      AI
      Causes a string to be displayed in the specified font size as if it were in a <font size="size"> tag.
      8
      AI
      Causes a string to be italic, as if it were in an <i> tag.
      9
      AI
      Creates an HTML hypertext link that requests another URL.
      10
      AI
      Causes a string to be displayed in a small font, as if it were in a <small> tag.
      11
      AI
      Causes a string to be displayed as struck-out text, as if it were in a <strike> tag.
      12
      AI
      Causes a string to be displayed as a subscript, as if it were in a <sub> tag
      13
      AI
      Causes a string to be displayed as a superscript, as if it were in a <sup> tag