replaceBefore

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

Usage

var replaceBefore = require( '@stdlib/string/replace-before' );

replaceBefore( str, search, replacement )

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

var out = replaceBefore( 'beep boop', ' ', 'loop' );
// returns 'loop boop'

out = replaceBefore( 'beep boop', 'o', 'bar' );
// returns 'baroop'

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.

Examples

var replaceBefore = require( '@stdlib/string/replace-before' );

var out = replaceBefore( 'beep boop', 'p', 'see' );
// returns 'seep boop'

out = replaceBefore( 'Hello World!', 'xyz', 'foo' );
// returns 'Hello World!'

out = replaceBefore( 'Hello World!', '', 'foo' );
// returns 'Hello World!'

out = replaceBefore( '', 'xyz', 'foo' );
// returns ''

CLI

Usage

Usage: replace-before [options] --search=<string> --replacement=<string> [<string>]

Options:

  -h,    --help                Print this message.
  -V,    --version             Print the package version.
         --search string       Search string.
         --replacement string  Replacement string.
         --split sep           Delimiter for stdin data. Default: '/\\r?\\n/'.

Notes

  • If the split separator is a regular expression, ensure that the split option is either properly escaped or enclosed in quotes.

    # Not escaped...
    $ echo -n $'foo\nbar\nbaz' | replace-before --search a --replacement b --split /\r?\n/
    
    # Escaped...
    $ echo -n $'foo\nbar\nbaz' | replace-before --search a --replacement b --split /\\r?\\n/
    
  • The implementation ignores trailing delimiters.

Examples

$ replace-before abcdefg --search d --replacement pqr
pqrdefg

To use as a standard stream,

$ echo -n $'beep\nboop' | replace-before --search p --replacement see
seep 
seep

By default, when used as a standard stream, the implementation assumes newline-delimited data. To specify an alternative delimiter, set the split option.

$ echo -n 'beep\tboop' | replace-before --search p --replacement see --split '\t'
seep 
seep
Did you find this page helpful?