[JS/C#] Replace {myVariable} in a String for the value.

Hey guys, is it possible to create a function, that’ll detect and replace any/predefined variables such as Screen.width in a string for the actual values? Example:

var myString : String = "The width of my screen is {Screen.width}px and the height is {Screen.height}px!!"

print(myString); //prints The width of my screen is 1920 and the height is 1080px!!

This is just an example. In real life scenario, I would have any number of {} in the strings that would use any combinations of the variables.

Also, I know about String.Format, but that (alone) isn’t what I am looking for.

If it is, could you point me in any general direction? Should I just scan the string for any { characters, and then pass everything that comes after until the next } to a function that’ll return the value?

– David

Debug.Log(String.Format(“The width of my screen is {0}px and the height is {1}px!!”,Screen.width,Screen.height));

You can use String.format.

var myString:String = String.Format("The width of my screen is {0}px and the height is {1}px!!", Screen.width, Screen.height);
print(myString);

It’s not as straightforward, but it works.

Console.WriteLine also allows the same syntax.

Console.WriteLine("The width of my screen is {0}px and the height is {1}px!!", Screen.width, Screen.height);

Personally, I normally do

print("The width of my screen is " + Screen.width + "px and the height is " + Screen.height + "px!!");

Alright, this is what I ended up doing:

function ParseVariables (str : String) {
	while(str.Contains("{")) {

		if(!str.Contains("}")) break;

		var substring : String = str.Substring(str.IndexOf("{")+1,str.IndexOf("}")-str.IndexOf("{")-1);
		str = str.Replace("{"+substring+"}",ParseVariablesValues(substring));
	}
	return str;
}

function ParseVariablesValues (substring : String) {
		
	var val : String = "unspecified";

	switch(substring) {
		case "Screen.height":
			val = Screen.height.ToString();
			break;
		case "Screen.width":
			val = Screen.width.ToString();
			break;
		default:
			val = "unspecified";
			break;
	}
	return val;
}

Usage:

var myString : String = "The width of my screen is {Screen.width}px and the height is {Screen.height}px!! I repeat, the screen is {Screen.height}px*{Screen.width}px {boo}{";
		
print(ParseVariables(myString)); //this prints The width of my screen is 446px and the height is 250px!! I repeat, the screen is 250px*446px unspecified{

– David