Strings in Javascript
JavaScript offers several methods and techniques for manipulating strings, lets read those methods and techniques.
Table of contents
Gone are the days of old string concatenation with the +
operator. In modern JavaScript, we have a better alternative: string interpolation. Let's see how it transforms our code.
Consider the following variables:
const name = "harsh";
const repoCount = "50";
console.log(name + " " + repoCount + " value"); //outputs: harsh 50 value
// This syntax is outdated and less readable
Lets read a better way to concatenate strings with the help of string interpolation
String Interpolation
Traditionally, concatenating strings using the +
operator could lead to repetition and less readable code. However, with the advantage of string interpolation, developers can now create more concise and readable string expressions. By using backticks (`) and placeholders ${}
, variables can be directly injected into the string, as shown below:
const name = "harsh";
const repoCount = "50";
console.log(`My name is ${name} and my repo count is ${repoCount}`);
//new method is to use back-ticks as here comes the concept of string
//interpolation in which we can create placeholders and directly inject
//variables inside those placeholders
String object and primitive string
Now let's understand a new way of declaring strings and understand the difference between string object and primitive string:
JavaScript provides two ways to declare strings: primitive strings and string objects. When a string is declared using the 'new' keyword and String
constructor function, it returns a string object rather than a primitive string value. While both types can be used interchangeably in most cases, string objects offer additional methods and properties for string manipulation:
const gameName = new String('harshh-hc');
console.log(gameName); // Outputs: [String: 'harshh-hc']
console.log(typeof(gameName)); // Outputs: object
//When you create a string using the String constructor function, it returns
//a string object rather than a primitive string value. This means that the
//value stored in gameName is not just a primitive string, but an instance of
// the String object.
String methods
JavaScript offers several string methods for performing various operations on strings. Here are a few commonly used ones:
toUpperCase()
: Converts a string to uppercase.charAt(index)
: Returns the character at the specified index.indexOf(substring)
: Returns the index of the first occurrence of a substring.substring(startIndex, endIndex)
: Returns a substring based on the specified indices.slice(startIndex, endIndex)
: Returns a portion of a string based on the specified indices, allowing negative indices for counting from the end of the string.trim()
: Removes whitespace from both ends of a string.replace(oldValue, newValue)
: Replaces occurrences of a specified value with another value.includes(substring)
: Checks if a string contains a specified substring.split(separator)
: Splits a string into an array of substrings based on a specified separator.
console.log(gameName[0]); //outputs: h
console.log(gameName.__proto__); // outputs: {}, provides the prototype and there are different methods in prototype and some are
console.log(gameName.length); //outputs: 9
console.log(gameName.toUpperCase()); //outputs: HARSHH-HC
console.log(gameName.charAt(2)); //outputs: r
console.log(gameName.indexOf('r')); //outputs: 2
console.log(url.split('-')); // Outputs: ['harshh', 'hc']
//few more
const newString = gameName.substring(0,4); //can not enter/pass negative value in substring function
console.log(newString);
//outputs: hars
const anotherString = gameName.slice(-8,4); //can pass negative value in slice function
console.log(anotherString);
//outputs: ars
Let's see some more methods to work with strings:
As sometimes there are many whitespaces in a string, to remove those spaces we use the trim function, consider this example:
const newStringOne = " harsh ";
console.log(newStringOne); //outputs: harsh
console.log(newStringOne.trim()); //outputs: harsh
Lets talk about a few more (probably last) function used for string manipulation in javascript:
const url = "https://harsh.com/harsh%20gupta";
console.log(url.replace('%20','-')); // Outputs: https://harsh.com/harsh-gupta
console.log(url.includes('harsh')); // Outputs: true
By leveraging these string manipulation techniques and methods, developers can write cleaner, more efficient code for handling textual data in JavaScript applications. Whether it's formatting strings, extracting substrings, or replacing characters, JavaScript offers a diverse array of tools to suit various string manipulation needs.