Loading
String in Javascript-tutorial
In JavaScript, a String is a sequence of characters used to represent text. Strings are one of the most commonly used data types and are enclosed in

  • Single quotes (' '),
  • Double quotes (" "), or
  • Backticks (` `) for template literals.



Ways to Create a String in JavaScript

JavaScript offers two main ways to create strings

  • String Literal
  • String Object (using new keyword)



String Literal

This is the simplest and most commonly used method to define a string.



Syntax:

var stringName = "Your string value";



Example:

<!DOCTYPE html>
<html>

<body>
    <script>
        var str = "Welcome to Quipoin";
        document.write(str);
    </script>
</body>

</html>

Output

Uploaded Image




String Object (using new keyword)

You can also crate a string by instantiating the String object using the new keyword.



Syntax:

var stringName = new String("Your string value");



Example:

<!DOCTYPE html>
<html>

<body>
    <script>
        var stringname = new String("hello javascript string");
        document.write(stringname);
    </script>
</body>

</html>

Output

Uploaded Image



Tip: While both methods create a string, using string literals is recommended because they are simpler and more efficient.