JavaScript Insert a string at position X of another string
Given 2 strings, the task is to insert one string in another at a specified position using javascript, we’re going to discuss a few techniques. First few methods to know.
JavaScript String slice() method: This method gets parts of a string and returns the extracted parts in a new string. Start and end parameters are used to specify the part of the string to extract. The first character starts from position 0, the second has position 1, and so on.
Syntax:
string.slice(start, end)
JavaScript Array join() Method: This method adds the elements of an array into a string and returns the string. The elements will be separated by a passed separator. The default separator is a comma (, ).
Syntax:
array.join(separator)
Example: This example inserts one string into another by using slice() and join() method.
Javascript
<body style= "text-align:center;" id= "body" > <h1 style= "color:green;" > GeeksForGeeks </h1> <h3> JavaScript | Insert string at position X of another string. </h3> <p id= "GFG_UP" style= "font-size: 19px; font-weight: bold;" > </p> <button onclick= "GFG_Fun(); " > click here </button> <p id= "GFG_DOWN" style= "color: green; font-size: 24px; font-weight: bold;" > </p> <script> var up = document.getElementById( 'GFG_UP' ); var down = document.getElementById( 'GFG_DOWN' ); var a = 'GeeksGeeks' ; var b = 'For' ; var pos = 5; up.innerHTML = 'Str_1 = "' + a + '"<br>Str_2 = "' + b + '"' ; function GFG_Fun() { down.innerHTML = [a.slice(0, pos), b, a.slice(pos)].join( '' ) } </script> </body> |
Output:

Insert a string at position X of another string
JavaScript String substr() Method: This method gets parts of a string, starting at the character at the defined position, and returns the specified number of characters.
Syntax:
string.substr(start, length)
Example: This example inserts one string to another by using substr() method.
Javascript
<body style= "text-align:center;" id= "body" > <h1 style= "color:green;" > GeeksForGeeks </h1> <h3> JavaScript | Insert string at position X of another string. </h3> <p id= "GFG_UP" style= "font-size: 19px; font-weight: bold;" > </p> <button onclick= "GFG_Fun(); " > click here </button> <p id= "GFG_DOWN" style= "color: green; font-size: 24px; font-weight: bold;" > </p> <script> var up = document.getElementById( 'GFG_UP' ); var down = document.getElementById( 'GFG_DOWN' ); var a = 'GeeksGeeks' ; var b = 'For' ; var pos = 5; up.innerHTML = 'Str_1 = "' + a + '"<br>Str_2 = "' + b + '"' ; function GFG_Fun() { down.innerHTML = a.substr(0, pos) + b + a.substr(pos); } </script> </body> |
Output:

Insert a string at position X of another string
Please Login to comment...