Replace

Replaces occurrences of substring1 in a string with obj, in a specified scope.

The search is case-sensitive. Function returns original string with replacements made

Method Signature

Replace(string=[string], substring1=[string], obj=[any], scope=[string])

Arguments

Argument
Type
Required
Description
Default

string

string

true

The string to search

substring1

string

true

The substring to search for

obj

any

true

The string to replace substring1 with

scope

string

true

The scope to search in

one

Examples

Replace uppercase 'U' with lowercase 'u'

Replace in Script Syntax

Run Example

getVal = replace( "Boxlang", "U", "u" );
writeDump( getVal );

Result: Boxlang

Replace uppercase 'O' with lowercase 'o', but only once

Something similar in Tag Syntax

Run Example

<bx:set getVal1 = replace( "Boxlang", "O", "o", "ONE" ) >
<bx:dump var="#getVal1#"/>

Result: Boxlang

Example using Callback Function

You can pass in a callback function to the third argument of the replace function

Run Example


public function upCase( Any pattern, Any position, Any orig ) {
	return uCase( pattern );
}
result = replace( "A man a plan a canal.", "an", upCase, "ALL" );
writeOutput( result );

Result: A mAN a plAN a cANal.

Example with start argument (Replace lowercase 'o' with uppercase 'O' from the third position)

You can pass position to start searching in the string

Run Example

getRes = replace( "Love Boxlang", "o", "O", "ALL", "3" );
writeOutput( getRes );

Result: Love Boxlang

Additional Examples

writeDump( replace( "xxabcxxabcxx", "abc", "def" ) );
writeDump( replace( "xxabcxxabcxx", "abc", "def", "All" ) );
writeDump( replace( "abc", "a", "b", "all" ) );
writeDump( replace( "a.b.c.d", ".", "-", "all" ) );
test = "camelcase CaMeLcAsE CAMELCASE";
test2 = Replace( test, "camelcase", "CamelCase", "all" );
writeDump( test2 );
replacer = ( Any find, Any index, Any input ) => {
	dump( var=arguments, label="replacement arguments" );
	return "-#index#-";
};
writeDump( var=replace( "one string, two strings, three strings", "string", replacer, "all" ), label="replace with a function" );
writeDump( var=replace( "one string, two strings, three strings", {
	"one" : 1,
	"two" : 2,
	"three" : 3,
	"string" : "txt",
	"text" : "string"
} ), label="replace via a struct" );
 // struct keys need to be quoted

Last updated

Was this helpful?