UNPKG

awesome-string

Version:

The ultimate JavaScript string library

45 lines (44 loc) 1.7 kB
import coerceToNumber from 'helper/number/coerce_to_number'; import coerceToString from 'helper/string/coerce_to_string'; /** * 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 * as.splice('new year', 0, 4); * // => 'year' * * as.splice('new year', 0, 3, 'happy'); * // => 'happy year' * * as.splice('new year', -4, 4, 'day'); * // => 'new day' */ export default function splice(subject, start, deleteCount, toAdd) { const subjectString = coerceToString(subject); const toAddString = coerceToString(toAdd); let startPosition = coerceToNumber(start); if (startPosition < 0) { startPosition = subjectString.length + startPosition; if (startPosition < 0) { startPosition = 0; } } else if (startPosition > subjectString.length) { startPosition = subjectString.length; } let deleteCountNumber = coerceToNumber(deleteCount, subjectString.length - startPosition); if (deleteCountNumber < 0) { deleteCountNumber = 0; } return subjectString.slice(0, startPosition) + toAddString + subjectString.slice(startPosition + deleteCountNumber); }