0

I have a string that comes from user: Below is an exact example

var message = "You purchased $name on $date"

Am within a Firebase Listener where variable querySnapshot is carrying data, how can looop through message and replace every occurence of $ to take the variable immediately after $ eg date and make the message be like below

message = "You purchased + querySnapshot.get("name") + on querySnapShot.get("date")

Thoughts: I imagine checking through the string message and finding all occurences of $ and getting the value after them. Then replacing $value with querySnapshot(value)...if you know how how i can implement this, kindly help out.

Kaita John
  • 907
  • 1
  • 5
  • 14
  • Where does the values come from? Some kind of map I suppose? – Nicolas Jun 13 '20 at 18:20
  • `var message = "You purchased ${querySnapshot.get("name")} on ${querySnapShot.get("date")}"` ? – IR42 Jun 13 '20 at 18:22
  • 3
    Does this answer your question? [How to replace multiple substring of a string at one time?](https://stackoverflow.com/q/38649267/5221149) – Andreas Jun 13 '20 at 18:26

1 Answers1

1

Not sure If this is what you are looking for

public static void main(String[] args) {
        String message  = "You purchased $name on $date";
        String[] arr = message.split(" ");

        for (int i = 0; i < arr.length; i++) {
            String s = arr[i];
            if (s.contains("$")) {
                arr[i] = "+ querySnapshot.get(" + "\"" + s.substring(1) + "\"" + ")";
            }
        }

        System.out.println(String.join(" ", arr));

    }
  • it is working, could you kindly modify your code to print "You purchased + ${ querySnapshot.get("name")} + on ${querySnapShot.get("date")} It is printing exactly as a string, putting those parameters will make it grab the dynamic data – Kaita John Jun 13 '20 at 19:21