insert.js 461 B

123456789101112131415161718192021
  1. var clamp = require('../math/clamp');
  2. var toString = require('../lang/toString');
  3. /**
  4. * Inserts a string at a given index.
  5. */
  6. function insert(string, index, partial){
  7. string = toString(string);
  8. if (index < 0) {
  9. index = string.length + index;
  10. }
  11. index = clamp(index, 0, string.length);
  12. return string.substr(0, index) + partial + string.substr(index);
  13. }
  14. module.exports = insert;