Jump to content
newcoder1010

How can I have a variable with single quotes

Recommended Posts

Hello,

//works
List textDemo = (List) driver.findElements(By.xpath("//*[contains(text(),'First Name is required.')]"));
//does not work
String name = "\'First Name is required.\'";
List textDemo = (List) driver.findElements(By.xpath("//*[contains(text(),name)]"));

First code has this 'First Name is required.' with single code inside double quotes.

Second code has a variable name which stores 'First Name is required.'. It is not working. How can I have name variable with single quotes 'First Name is required.'?

 

Share this post


Link to post
Share on other sites

Do you really need escaped single quotes? Passing it as a string variable  in either single or double quotes then comparing to another string value with text() won't make any difference.

 

Share this post


Link to post
Share on other sites
// here it works just fine. If and else works as expected
List textDemo = (List) driver.findElements(By.xpath("//*[contains(text(),'First Name is required8.')]"));
if(((java.util.List<String>) textDemo).isEmpty())
{
System.out.println("Element using text is not found");
}
		 
else
System.out.println("Element using text is found");
}
// here only else block is being executed every time regardless I have correct value or not. 
String x = "\'First Name is required wrong value.\'"; // I also tried without the single quotes and escaped \ inside double quotes
System.out.println("x " + x);
List textDemo = (List) driver.findElements(By.xpath("//*[contains(text(),x)]"));
if(((java.util.List<String>) textDemo).isEmpty())
{
System.out.println("Element using text is not found");
}
else
System.out.println("Element using text is found");
}

This is selenium java webdriver/java related issues. I have problem only when I store the string in a variable. I am not sure how to fix it. 

Edited by newcoder1010

Share this post


Link to post
Share on other sites

Xpath can't read Java variables. You have to put the variable outside of the string.

"//*[contains(text(),'" + x + "')]"

 

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...