Question
· Apr 19, 2023

Replace text by args

Hi all,

I'm wondering if exists any command or method to replace a text using parameters.

In C# I use the Format property

var text = string.format("My name is {0} and I'm {1} years","Kurro","18")
// The value of text will be "My name is Kurro and I'm 18 years"

I've tried with this code... but it works only for the specific parameters

set text = "My name is {0}, and I'm {1} years"
write $Replace($Replace(text,"{0}","Kurro"),"{1}",18)

is possible to do something for more args? I mean, use for a indeterminate number of args

 

Best regads

Product version: IRIS 2022.1
$ZV: IRIS for Windows (x86-64) 2021.1 (Build 215U) Wed Jun 9 2021 09:39:22 EDT
Discussion (11)3
Log in or sign up to continue

PS.: it also works if you concatenate strings:
 

write "my string"_stringVariable_"continue string"

In the first case you would be calling the "WRITE" method 3 times, once for each string divided by ",", and in the second you would be calling "WRITE" once with only one string that is a copy of the 3 strings combined together. 

You could also use concatenating to set a new variable:
 

Set stringVariable = " | "
Set stringsCombined = "my string"_stringVariable_"continue the string"

And then you can work with this new variable.

I.E. if you called WRITE stringsCombined, you would have as an output:

my string | continue the string

Hey Kurro.

I'm not sure of a built in function for this, but if you wanted to have your own:

Class Demo.FunctionSets.Example
{

ClassMethod Format(InputString As %String, Params... As %String) As %String
{
	Set OutputString = InputString
	For i = 1 : 1 : $GET(Params, 0){
		Set OutputString = $Replace(OutputString,"{"_i_"}",Params(i))
	}
	
	Quit OutputString
}

}

And then:

Write ##Class(Demo.FunctionSets.example).Format("My name is {1} and I'm {2} years","Kurro","18")
My name is Kurro and I'm 18 years