UNPKG

voca

Version:

The ultimate JavaScript string library

58 lines (48 loc) 1.87 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'); /** * Changes `subject` by deleting `deleteCount` of characters starting at position `start`. Places a new string * `toAdd` instead of deleted characters. * * @function splice * @static * @since 1.0.0 * @memberOf Manipulate * @param {string} [subject=''] The string where to insert. * @param {string} start The position to start changing the string. For a negative position will start from the end of * the string. * @param {number} [deleteCount=subject.length-start] The number of characters to delete from string. * @param {string} [toAdd=''] The string to be added instead of deleted characters. * @return {string} Returns the modified string. * @example * v.splice('new year', 0, 4); * // => 'year' * * v.splice('new year', 0, 3, 'happy'); * // => 'happy year' * * v.splice('new year', -4, 4, 'day'); * // => 'new day' */ function splice(subject, start, deleteCount, toAdd) { var subjectString = coerce_to_string.coerceToString(subject); var toAddString = coerce_to_string.coerceToString(toAdd); var startPosition = coerce_to_number.coerceToNumber(start); if (startPosition < 0) { startPosition = subjectString.length + startPosition; if (startPosition < 0) { startPosition = 0; } } else if (startPosition > subjectString.length) { startPosition = subjectString.length; } var deleteCountNumber = coerce_to_number.coerceToNumber(deleteCount, subjectString.length - startPosition); if (deleteCountNumber < 0) { deleteCountNumber = 0; } return subjectString.slice(0, startPosition) + toAddString + subjectString.slice(startPosition + deleteCountNumber); } module.exports = splice;