Eliminates redundant spaces from the supplied string.
normalize-space function is a part of string function in XPath. The normalize-space function takes a string argument and matches the string present in the document/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.
normalize-space(string) 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 webdriver.
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.