replace, replace all

Prev Next

Function Names

replace, replace all

Description

The function replace replaces the first occurrence of the specified old contents by new contents.
The function replace all replaces all occurrences of the specified old contents by new contents.

Comparing wtih the substitute() function, the 1st parameter is an input parameter and the return value contains the modified string.
substitute( a[], "Hello", "Hi" ); is the same as a[] = replace( a[], "Hello", "Hi" );

Call as: function

Restrictions

Indirect parameter passing is disabled

Parameter count

3-4

Parameters

No.TypeDescription
1
input
string input string

Input string with contents to replace

2
input
parameter set or string existing contents

If provided as a string: The string will be looked for this content.
If provided as a parameter set: The string will be looked for all contents provided in the parameter set.
Attention: No wildcard symbols are supported here.

3
input
parameter set or string new contents

These new contents will be inserted.
If provided as a string: New contents to replacing the identified old contents.
If provided as a parameter set: Number of elements must either be equal to the number of elements in the 2nd function parameter, or just 1 element

Opt. 4
input
numeral starting position

String replacement begins at a specified characcter position. For example, 2 skips the first two chracters in the input string.

Default value: 0

Return value

TypeDescription
string String wîth replaced contents

Exceptions

3rd parameter contains different number of elements than 2nd parameter, and is not 1

Examples

      st[] = "the house, the mouse, and the spouse";

      echo( replace     ( st[], the, a ) );
      echo( replace all ( st[], the, a ) );

      // First occurrence of each term
      echo( replace     ( st[], { the, spouse, mouse, house }, { THE, SPOUSE, MOUSE, HOUSE } ) );

      // All occurrences.  See difference on 'the'
      echo( replace all ( st[], { the, spouse, mouse, house }, { THE, SPOUSE, MOUSE, HOUSE } ) );

      echo( replace all ( st[], { spouse, mouse, house }, { one } ) ); // Replace all by 'home'

      echo( replace    ( "Café Café Café", Café, Caffè, 1 ) ); // Skip first 'Café'
      echo( replace all( "Café Café Café", Café, Caffè, 1 ) ); // Skip first 'Café'

Output

a house, the mouse, and the spouse
a house, a mouse, and a spouse
THE HOUSE, the MOUSE, and the SPOUSE
THE HOUSE, THE MOUSE, and THE SPOUSE
the one, the one, and the one
Café Caffè Café
Café Caffè Caffè
Try it yourself: Open LIB_Function_replace.b4p in B4P_Examples.zip. Decompress before use.

See also

substitute
substitute all