XQuery: removing newline/return character from end of a string stored in a variable in query

Arvind picture Arvind · Sep 19, 2012 · Viewed 9.7k times · Source

How do I remove a new-line/return from the end of a variable? I tried functx:substring-before-last to try and remove the new line (denoting it as \r, \n and also as \r\n) but still when I output that variable's value, the newline is still there in it.

Answer

Leo Wörteler picture Leo Wörteler · Sep 19, 2012

You can either use fn:normalize-space($arg as xs:string?) to remove all additional whitespace:

Summary: Returns the value of $arg with whitespace normalized by stripping leading and trailing whitespace and replacing sequences of one or more than one whitespace character with a single space, #x20.

Or you can just use fn:replace(..) and a regular expression:

fn:replace($string, '(\r?\n|\r)$', '')