Open In App

How to modify a string in JavaScript ?

Last Updated : 14 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

JavaScript strings are used for storing and manipulating text. It can contain zero or more characters within quotes and its indexing starts with 0. Strings are defined as an array of characters. In Javascript, we can also convert strings to a Character array. 

Representing a String: 

1. Using double quotes or single quotes.

Javascript




<script>
  
    // With single quotes
    let string1 = 'GFG!';
    console.log(string1);
      
    // With double quotes
    let string2 = "Geeks for Geeks"
    console.log(string2);
</script>


Output:

GFG!
Geeks for Geeks

2. Quotes can be used inside a string, as long as they don’t match the quotes surrounding the string. 

Javascript




<script>
  
    // Using double quotes inside a string
    let string1 = 'GFG is "Awesome"!';
    console.log(string1);
      
    // Using single quotes inside a string
    let string2 = "'Geeks' for 'Geeks'";
    console.log(string2);
</script>


Output:

GFG is "Awesome"!
'Geeks' for 'Geeks'

3. Strings can be used as objects by using the keyword ‘new’. 

Javascript




<script>
    let str = new String("GFG");
    console.log(str);
</script>


Output:

[String: 'GFG']

4. We can also use special characters by using a backslash(\).

Javascript




<script>
    let string1 = "Hello, \'Sam\' is using \"Geeks for Geeks\"";
    console.log(string1);
</script>


Output:

Hello, 'Sam' is using "Geeks for Geeks"

In Javascript, strings are immutable, i.e. we can’t modify them using indexes. But there are some ways, we can modify a javascript string. Let’s see various methods of doing it.

Method 1: We can use replace() method. The str.replace(A, B) method will return a string in which A in str has been replaced by B.

Javascript




<script>
    let string1 = "GFG is Awesome";
    console.log("Before Replacing : ",string1);
    let string2 = string1.replace("GFG" , "Geeks For Geeks");
    console.log("After  Replacing : ",string2);
</script>


Output:

Before Replacing :  GFG is Awesome
After  Replacing :  Geeks For Geeks is Awesome

Method 2: Using the substring method to insert a character or string at a given index. string1.substring(0,pos) + ‘a’ + string1.substring(pos) will return a string in which ‘a’ is inserted at index pos in string1.

Javascript




<script>
    let string1 = "helo";
    console.log(string1);    
    let string2 = string1.substring(0,2) 
        + 'l' + string1.substring(2);
    console.log(string2);
</script>


Output:

helo
hello

Method 3: By converting the string to a character array and then modifying the character array and then merging the character array to a string. To convert string to character arrays, we have 4 ways.

  • split(): It returns an array by splitting the string.
  • spread operator ( […string] ): It returns an array.
  • Array.from(): It returns an array from a string.
  • Object.assign([], string): It returns an array by assigning string characters to it.

To convert the character array to the string we use 

  • s.join(“”):  It returns a string by joining all items of the array.

Javascript




<script>
    let name = 'GFGWebsite';
      
    // Using split
    let arr1 = name.split('');
    arr1[0]='A';
    let string1 = arr1.join("");
    console.log(string1);
      
    // Using spread operator
    let arr2 = [...name];
    arr2[1]='B';
    arr2[2]='C';
    let string2 = arr2.join("");
    console.log(string2);
      
    // Using Array.from
    let arr3 = Array.from(name);
    arr3[1]='-';
    let string3 = arr3.join("");
    console.log(string3);
      
    // Using Object.assign
    let arr4 = Object.assign([], name);
    arr4[5]='+';
    let string4 = arr4.join("");
    console.log(string4);
</script>


Output:

AFGWebsite
GBCWebsite
G-GWebsite
GFGWe+site


Similar Reads

Javascript Program to Modify a string by performing given shift operations
Given a string S containing lowercase English alphabets, and a matrix shift[][] consisting of pairs of the form{direction, amount}, where the direction can be 0 (for left shift) or 1 (for right shift) and the amount is the number of indices by which the string S is required to be shifted. The task is to return the modified string that can be obtain
3 min read
Javascript Program to Modify a matrix by rotating ith row exactly i times in clockwise direction
Given a matrix mat[][] of dimensions M * N, the task is to print the matrix obtained after rotating every ith row of the matrix i times in a clockwise direction. Examples: Input: mat[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}Output:1 2 36 4 58 9 7Explanation:The 0th row is rotated 0 times. Therefore, the 0th row remains the same as {1, 2, 3}.The 1st r
3 min read
Different Types of DOM Available to Access and Modify Content in JavaScript
The Document Object Model (DOM) enables developers to access and control web page elements using scripting languages like JavaScript, it is a crucial part of web development. There are various DOM types that can be accessed and modified with JavaScript. The various DOM types offered by JavaScript, their capabilities, and their applications in web d
3 min read
How to modify URL without reloading the page using JavaScript ?
In this article, we are going to see how to modify URL without reloading the page using JavaScript Below are the methods to modify the URL without reloading the page using JavaScript: Table of Content Replacing the current state with replaceState() MethodAdding a new state with pushState() MethodMethod 1: Replacing the current state with replaceSta
3 min read
How to modify an object's property in an array of objects in JavaScript ?
Modifying an object's property in an array of objects in JavaScript involves accessing the specific object within the array and updating its property. In this article we are going to see how to modify an object's property in an array of objects in JavaScript Below are the approaches to modify an object's property in an array of objects in JavaScrip
5 min read
JSON Modify an Array Value of a JSON Object
The arrays in JSON (JavaScript Object Notation) are similar to arrays in JavaScript. Arrays in JSON can have values of the following types: nullbooleannumberstringarrayobject The arrays in JavaScript can have all these but it can also have other valid JavaScript expressions which are not allowed in JSON. The array value of a JSON object can be modi
2 min read
PHP | DateTime modify() Function
The DateTime::modify() function is an inbuilt function in PHP which is used to modify or can alter the timestamp of a DateTime object. Syntax: Object oriented style: DateTime DateTime::modify( string $modify ) Procedural style: DateTime date_modify( DateTime $object, string $modify ) Parameters: This function uses two parameters as mentioned above
2 min read
PHP | DateTimeImmutable modify() Function
The DateTimeImmutable::modify() function is an inbuilt function in PHP which is used to modify or alter the timestamp of the created DateTimeImmutable object. Syntax: DateTimeImmutable DateTimeImmutable::modify( string $modify ) Parameters: This function uses two parameters as mentioned above and described below: object: This parameter holds the Da
2 min read
How to modify CSS class using jQuery library ?
In this article, we will discuss how to modify the css class using jQuery. This is one of the major applications of jQuery. We generally use it when we have to add a dynamic style of the particular element of the HTML. For example, changing the color of particular class content dynamically. Approach: We will use addclass(), css(), and some other me
5 min read
Which property can be used to modify the content of HTML element ?
In this article, we will see the property that can be used to modify the content of HTML element. To modify the content of HTML element, we will use HTML DOM innerHTML Property. The innerHTML Property is used to set or return the content of HTML element. Syntax: It returns the content of an element. Object.innerHTML It is used to set the content of
2 min read