replace-string
Advanced tools
Comparing version 1.0.0 to 1.1.0
20
index.js
'use strict'; | ||
module.exports = (input, needle, replacement) => { | ||
module.exports = (input, needle, replacement, opts) => { | ||
opts = Object.assign({}, opts); | ||
if (typeof input !== 'string') { | ||
@@ -14,4 +16,8 @@ throw new TypeError(`Expected input to be a string, got ${typeof input}`); | ||
let matchCount = 0; | ||
let prevIndex = 0; | ||
let prevIndex = opts.fromIndex > 0 ? opts.fromIndex : 0; | ||
if (prevIndex > input.length) { | ||
return input; | ||
} | ||
while (true) { // eslint-disable-line no-constant-condition | ||
@@ -28,7 +34,15 @@ const index = input.indexOf(needle, prevIndex); | ||
ret += input.slice(prevIndex, index) + replaceStr; | ||
// Get the initial part of the string on the first iteration | ||
const beginSlice = matchCount === 1 ? 0 : prevIndex; | ||
ret += input.slice(beginSlice, index) + replaceStr; | ||
prevIndex = index + needle.length; | ||
} | ||
if (matchCount === 0) { | ||
return input; | ||
} | ||
return ret + input.slice(prevIndex); | ||
}; |
{ | ||
"name": "replace-string", | ||
"version": "1.0.0", | ||
"version": "1.1.0", | ||
"description": "Replace all substring matches in a string", | ||
@@ -5,0 +5,0 @@ "license": "MIT", |
@@ -29,3 +29,3 @@ # replace-string [![Build Status](https://travis-ci.org/sindresorhus/replace-string.svg?branch=master)](https://travis-ci.org/sindresorhus/replace-string) | ||
### replaceString(input, needle, replacement) | ||
### replaceString(input, needle, replacement, [options]) | ||
@@ -59,3 +59,14 @@ Returns a new string with all `needle` matches replaced with `replacement`. | ||
#### options | ||
Type: `Object` | ||
##### fromIndex | ||
Type: `number`<br> | ||
Default: `0` | ||
Index at which to start replacing. | ||
## Related | ||
@@ -62,0 +73,0 @@ |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
4590
33
78