3 JavaScript Strings 10xtechinfinity 1731085819
3 JavaScript Strings 10xtechinfinity 1731085819
Strings are one of the most fundamental data types in JavaScript. They're used to
represent and manipulate text. In this guide, we'll explore various aspects of
JavaScript strings, from creation to manipulation and conversion.
Creating Strings
In JavaScript, you can create strings in two main ways:
The String() constructor creates a String object, not a primitive string value.
JavaScript Strings 1
You can get the length of a string using the length property:
console.log(string1.length); // 11
console.log(string2.length); // 12
Accessing Characters
You can access individual characters in a string using either the charAt() method
or square bracket notation:
console.log(string1.charAt(1)); // a
console.log(string2[11]); // d
The eval() function treats string primitives and String objects differently.
Template Literals
JavaScript Strings 2
Template literals are a modern and preferred way to create strings, especially
when you need to include variables or expressions:
String Concatenation
While you can concatenate strings using the + operator, it's generally considered
a less elegant approach:
String Immutability
Strings in JavaScript are immutable, meaning they cannot be changed after
creation:
String Comparisons
Strings are compared character-by-character in alphabetical order:
JavaScript Strings 3
console.log("Manoj" > "Nishad"); // false: ASCII code of 'N' is
The String constructor creates a String object, while the String function creates a
primitive string.
String Conversion
Number to String
You can convert numbers to strings in two ways:
JavaScript Strings 4
String to Number
Similarly, you can convert strings to numbers:
Conclusion
Strings are a fundamental part of JavaScript, and understanding how to create,
manipulate, and convert them is crucial for any developer.
Remember to prefer string primitives over String objects, use template literals for
complex string creation, and be aware of the immutability of strings. With these
concepts in mind, you'll be well-equipped to handle text data in your JavaScript
applications.
Happy coding!
JavaScript Strings 5