What is the string object and why are using the string in JS.

Asked 19-Jul-2021
Viewed 352 times

1 Answer


2

The String object lets you work with a series of characters; it wraps JavaScript 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. A String is a collection of characters (or) sequence of characters, which is always enclosed with a single (‘’) or double quotes (“”). A JavaScript string stores a series of characters like “MindStick”.
• It is used to storing single characters, and
• It stores an array of characters
• It is used to manipulating text – search a particular letter and replace text
Note
It is immutable, the string cannot be changed in JavaScript. It is impossible to change a particular character.
Creation of string
• By string literal
var string-name = “string value”;
zero or more characters written inside single or double quotes or backticks. The string indexes are zero-based, the first character is in position 0 and the second in 1.
• By string object using ‘new’ keyword
var string name = new string (“string value”);
In this, a new keyword is used to create an instance of a string. The string object has some disadvantages, for example, the execution speed is slow.
String literals
<!DOCTYPE html>

<html lang='en' xmlns='http://www.w3.org/1999/xhtml'>
<head>
    <meta charset='utf-8' />
    <title></title>
</head>
<body>
    <h2>String </h2>
    <script type='text/javascript'>
        var name = ' Welcome Ravi, '; //literal
        var dept = 'MCA'
        document.write(name);
        document.write('He is ' + dept + ' department');
    </script>
</body>
</html>
String object
<!DOCTYPE html>

<html lang='en' xmlns='http://www.w3.org/1999/xhtml'>
<head>
    <meta charset='utf-8' />
    <title></title>
</head>
<body>
    <h2>String </h2>
    <script type='text/javascript'>
        var name = new String(' Welcome Ravi, '); //literal
        var dept = 'MCA'
        document.write(name);
        document.write('He is ' + dept + ' department');
    </script>
</body>
</html>