Skip to content

Latest commit

 

History

History
128 lines (77 loc) · 3.2 KB

File metadata and controls

128 lines (77 loc) · 3.2 KB

replaceBeforeLast

Replace the substring before the last occurrence of a specified search string.

Usage

var replaceBeforeLast = require( '@stdlib/string/base/replace-before-last' );

replaceBeforeLast( str, search, replacement, fromIndex )

Replaces the substring before the last occurrence of a specified search string.

var str = 'beep boop';
var out = replaceBeforeLast( str, ' ', 'loop', str.length );
// returns 'loop boop'

out = replaceBeforeLast( str, 'o', 'bar', str.length );
// returns 'barop'

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 is less than 0 or greater than the search string length, the function returns the provided string unchanged.

Examples

var replaceBeforeLast = require( '@stdlib/string/base/replace-before-last' );

var str = 'beep boop';
var out = replaceBeforeLast( str, 'p', 'see', str.length );
// returns 'seep'

str = 'Hello World!';
out = replaceBeforeLast( str, 'xyz', 'foo', str.length );
// returns 'Hello World!'

str = 'Hello World!';
out = replaceBeforeLast( str, '', 'foo', str.length );
// returns 'Hello World!'

str = '';
out = replaceBeforeLast( str, 'xyz', 'foo', str.length );
// returns ''