replaceBefore
Replace the substring before the first occurrence of a specified search string.
Usage
var replaceBefore = require( '@stdlib/string/base/replace-before' );
replaceBefore( str, search, replacement, fromIndex )
Replaces the substring before the first occurrence of a specified search string.
var out = replaceBefore( 'beep boop', ' ', 'loop', 0 );
// returns 'loop boop'
out = replaceBefore( 'beep boop', 'o', 'bar', 0 );
// returns 'baroop'
To begin searching from a specific index, provide a corresponding fromIndex
argument.
var out = replaceBefore( 'beep boop', 'p', 'bar', 5 );
// returns 'barp'
If fromIndex
is less than zero, the starting index is resolved relative to the last string character, with the last string character corresponding to fromIndex = -1
.
var out = replaceBefore( 'beep boop beep', ' ', 'loop', -6 );
// returns 'loop beep'
Notes
- If a search string is not present in a provided string, the function returns the provided string unchanged.
- If a search string is an empty string, the function returns the provided string unchanged.
- If
fromIndex
resolves to an index which is greater than or equal tostr.length
, the function returns the provided string unchanged.
Examples
var replaceBefore = require( '@stdlib/string/base/replace-before' );
var out = replaceBefore( 'beep boop', 'p', 'see', 0 );
// returns 'seep boop'
out = replaceBefore( 'Hello World!', 'xyz', 'foo', 0 );
// returns 'Hello World!'
out = replaceBefore( 'Hello World!', '', 'foo', 0 );
// returns 'Hello World!'
out = replaceBefore( '', 'xyz', 'foo', 0 );
// returns ''