UNPKG

voca

Version:

The ultimate JavaScript string library

40 lines (33 loc) 1.21 kB
'use strict'; require('./internal/is_nil.js'); require('./is_string.js'); var coerce_to_string = require('./internal/coerce_to_string.js'); var coerce_to_number = require('./internal/coerce_to_number.js'); /** * Inserts into `subject` a string `toInsert` at specified `position`. * * @function insert * @static * @since 1.0.0 * @memberOf Manipulate * @param {string} [subject=''] The string where to insert. * @param {string} [toInsert=''] The string to be inserted. * @param {number} [position=0] The position to insert. * @return {string} Returns the string after insertion. * @example * v.insert('ct', 'a', 1); * // => 'cat' * * v.insert('sunny', ' day', 5); * // => 'sunny day' */ function insert(subject, toInsert, position) { var subjectString = coerce_to_string.coerceToString(subject); var toInsertString = coerce_to_string.coerceToString(toInsert); var positionNumber = coerce_to_number.coerceToNumber(position); if (positionNumber < 0 || positionNumber > subjectString.length || toInsertString === '') { return subjectString; } return subjectString.slice(0, positionNumber) + toInsertString + subjectString.slice(positionNumber); } module.exports = insert;