I'm working with c# and Selenium, only way that worked for me was by splitting the string at (') and combine them using concat
function. This is a small method I used to achieve my goal.
This method takes two input parameters: inputString
and originalXpath
.
If inputString
does not contain any single quotes, the method simply returns the originalXpath
string formatted with the inputString
parameter using the string.Format()
method.
If inputString
does contain single quotes, the method replaces each single quote with ', "'", '
using the Replace()
method and concatenates the resulting string with the concat()
function. It then replaces the placeholder ' {0} '
in the originalXpath
string with the replacementString
created in the previous step using the Replace()
method. Finally, the method returns the resulting string.
In summary, this method formats an XPath string with an input parameter, using a concat()
function to handle cases where the input parameter contains single quotes.
using System;
using System.Linq;
public class Program
{
public static void Main()
{
string originalXpath = "//div[contains(., '{0}')]";
string inputString = "bjhe'bf83785*^{}^$#%!'edferferf'034**()";
string output = FormatWithConcat(inputString, originalXpath);
Console.WriteLine(output);
// Output: //div[contains(., concat('bjhe', "'", 'bf83785*^{}^$#%!', "'", 'edferferf', "'", '034**()'))]
}
private static string FormatWithConcat(string inputString, string originalXpath)
{
if (!inputString.Contains('\''))
{
return string.Format(originalXpath, inputString);
}
string replacementString = "concat('" + inputString.Replace("'", "', \"'\", '") + "')"; // Replace single quotes and concatenate with 'concat' function
string finalString = originalXpath.Replace("'{0}'", replacementString); // Replace the placeholder '{0}' in the original XPath with the replacement string
return finalString;
}
}
Equivalent Java code is:
public static String FormatWithConcat(String inputString, String originalXpath) {
if (!inputString.contains("'")) {
return String.format(originalXpath, inputString);
}
String replacementString = "concat('" + inputString.replaceAll("'", "', \"'\", '") + "')";
String finalString = originalXpath.replace("'{0}'", replacementString);
return finalString;
}
.NET Fiddle