Java Insert variable value in the middle of a string Locator or a URL.
I want to add a String variable value within an another String variable. I could use concatenation but is there any better way?
We could parameterize the text we want to add middle of it like below.
'" + text + "'
Here is the full code snippet.
String text="666";
String subject="Knowledge base '" + text + "' Approval Request";
This comes handy when capturing elements in Webdriver using Span text, or any scenario where some part of text is changed and can be parameterized.
public static void clickUsingSpanText(String text,WebDriver driver){
driver.findElement(By.xpath("//span[contains(text(),'" + text + "')]")).click();
}
public static void clickUsingNormalizedSpanText(String text,WebDriver driver){
driver.findElement(By.xpath("//span[contains(normalize-space(),'" + text + "')]")).click();
}
Another example is
String linkText=knowledgeArticleNumber+" - "+"666";
String element=driver.findElement(By.xpath("//a[contains(text(),'" + linkText + "')]")).getAttribute("innerText");
Also let’s look at a scenario where you have to parameterize a URL with a String variable when you are automating an API with Rest-Assured.
I want to parameterize 3f1dd0320a0a0b99000a53f7604a2ef9 value of below URL.
https://pineapples.com/api/sn_sc/v1/fruit/items/3f1dd0320a0a0b99000a53f7604a2ef9/submit_producer
So I declared it in to a variable and using “+sys_ID+” I pass it.
String sys_ID = "3f1dd0320a0a0b99000a53f7604a2ef9";RestAssured.baseURI = "https://pineapples.com";
RestAssured.basePath = "api/sn_sc/v1/fruits/items/"+sys_ID+"/submit_producer";