0

I have checked few of the existing questions but could not find any matching case.

I have a index.jsp page with ten variables declared and value assigned , an user from UI input text box can provide any value along with our existing variable with '@' prefix

eg 1: userinput = a=@useremail&b=c&d=@city  
    expected output : a=test@email&b=c&d=newyork  
    eg 2: userinput = a=b&c=@firstname  
    expected output : a=b&c=mark

with variable declared as below

String useremail = "test@email.com"
String lastname = "tony"
String firstname = "mark"
String city = "newyork"
String country = "US"

Now I need to replace these variables with actual values , if have tried with below snippet

if (inputText.contains("@")) {
    
    if (inputText.contains("@useremail")) 
        inputText = inputText.replace("@useremail",useremail);
    else if  (inputText.contains("@lastname"))
         inputText = inputText.replace("@lastname", lastname);
    else if  (inputText.contains("@firstname"))
        inputText = inputText.replace("@firstname", firstname);

    //need to check for all variables
}

I find trouble in using switch case as the value is a substring of the userinput, please help me to execute the case with best practices.

Thank you.

BKK
  • 340
  • 2
  • 4
  • 15
  • 1
    It is only going to `replace` if it `contains` so there is no point doing the `contains` first. – Scary Wombat Apr 22 '21 at 05:44
  • 3
    `inputText.replace("@useremail",buyerEmail).replace("@lastname", lastname).replace("@firstname", firstname)` – Scary Wombat Apr 22 '21 at 05:46
  • Thank you for your suggestion., but user input may or may not contain @variable name all the time and not necessarily with all variables so inputText.replace("@useremail",buyerEmail).replace("@lastname", lastname).replace("@firstname", firstname) can not be done always and for all variables.. – BKK Apr 22 '21 at 05:52
  • @KiranKumar in that case your question is not clear... – Nir Alfasi Apr 22 '21 at 06:07
  • 1
    @KiranKumar it does not matter if the input contains `@variable` If it does not exist then the string will not be changed – Scary Wombat Apr 22 '21 at 06:45

0 Answers0