Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting string at position x of another string

Tags:

javascript

I have two variables and need to insert string b into string a at the point represented by position. The result I'm looking for is "I want an apple". How can I do this with JavaScript?

var a = 'I want apple'; var b = ' an'; var position = 6; 
like image 566
sami Avatar asked Dec 06 '10 09:12

sami


People also ask

How do I append to a specific index of a string?

The splice() method is used to insert or replace contents of an array at a specific index. This can be used to insert the new string at the position of the array. It takes 3 parameters, the index where the string is to be inserted, the number of deletions to be performed if any, and the string to be inserted.

Which of the following method inserts a string at specified index position?

C# | Insert() Method In C#, Insert() method is a String method. It is used to return a new string in which a specified string is inserted at a specified index position in the current string instance.

How do you add a character to the front of a string?

1. Using String. Insert a character at the beginning of the String using the + operator. Insert a character at the end of the String using the + operator.


2 Answers

var a = "I want apple";  var b = " an";  var position = 6;  var output = [a.slice(0, position), b, a.slice(position)].join('');  console.log(output);

Optional: As a prototype method of String

The following can be used to splice text within another string at a desired index, with an optional removeCount parameter.

if (String.prototype.splice === undefined) {    /**     * Splices text within a string.     * @param {int} offset The position to insert the text at (before)     * @param {string} text The text to insert     * @param {int} [removeCount=0] An optional number of characters to overwrite     * @returns {string} A modified string containing the spliced text.     */    String.prototype.splice = function(offset, text, removeCount=0) {      let calculatedOffset = offset < 0 ? this.length + offset : offset;      return this.substring(0, calculatedOffset) +        text + this.substring(calculatedOffset + removeCount);    };  }    let originalText = "I want apple";    // Positive offset  console.log(originalText.splice(6, " an"));  // Negative index  console.log(originalText.splice(-5, "an "));  // Chaining  console.log(originalText.splice(6, " an").splice(2, "need", 4).splice(0, "You", 1));
.as-console-wrapper { top: 0; max-height: 100% !important; }
like image 70
jAndy Avatar answered Sep 28 '22 07:09

jAndy


var output = a.substring(0, position) + b + a.substring(position); 

Edit: replaced .substr with .substring because .substr is now a legacy function (per https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr)

like image 20
nickf Avatar answered Sep 28 '22 06:09

nickf