UNPKG

voca

Version:

The ultimate JavaScript string library

56 lines (47 loc) 1.78 kB
import './internal/is_nil.js'; import './is_string.js'; import { c as coerceToString } from './internal/coerce_to_string.js'; import { c as coerceToNumber } from './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 = coerceToString(subject); var toAddString = coerceToString(toAdd); var startPosition = coerceToNumber(start); if (startPosition < 0) { startPosition = subjectString.length + startPosition; if (startPosition < 0) { startPosition = 0; } } else if (startPosition > subjectString.length) { startPosition = subjectString.length; } var deleteCountNumber = coerceToNumber(deleteCount, subjectString.length - startPosition); if (deleteCountNumber < 0) { deleteCountNumber = 0; } return subjectString.slice(0, startPosition) + toAddString + subjectString.slice(startPosition + deleteCountNumber); } export default splice;