The normalize-space function in XPath ignores all redundant spaces in a target string HTML element and matches with a given value. normalize-space() function takes a string argument and matches the attribute values present on the webpage.
The normalize-space function ignores the leading, trailing, and repeating white spaces, which means after applying the normalize-space the text becomes normalized with no line breaks and gives a proper sentence.
The syntax for normalize space
//tagname[normalize-space(function/attribute), "given"]
str = " cher cher tech "
normalize-space(string) // outputs "cher cher tech"
We can create an XPath using the normalize space, these kinds of XPaths will be useful when we want to match an element but which has leading/trailing spaces or more spaces between words.
XPath normalize-space text example
html code
<label> who cares about spaces </label>
xpath
//label[normalize-space(text())='who cares about spaces']
Not only developers use the XPath but testers also do use XPath for automating the application. normalize space plays an important role in selenium automation where we have to find the elements on the webpage and perform some action on it with the web driver.
driver.findElement(By.xpath(
"//label[normalize-space(text())='who cares about spaces']"
)).click()
normalize-space('query') --> query
normalize-space(' query ') --> query
normalize-space('xml query') --> xml query
normalize-space('xml query') --> xml query
normalize-space('xml
query') --> xml query
normalize-space('') --> zero-length string
normalize-space(' ') --> zero-length string
normalize-space(()) --> zero-length string
normalize-space( query ) --> query
So far we have seen how to use the normalize space with text, normalize-space can also work with an attribute that has spaces and newlines
html code
<label id='has random spaces '>text </label>
xpath
//label[normalize-space(@id)='has random spaces']
We can also match the partial match using the normalize-space with contains() function present in the XPath. Rewriting the above example using contains with normalize-space
html code
<label id='has random spaces '>text </label>
xpath
//label[contains(normalize-space(@id),'has random')]
The XPath does not depend on the programming languages like Java, C#, Python, or any other but it always depends on the HTML document or XML document.
I am Pavankumar, Having 8.5 years of experience currently working in Video/Live Analytics project.