xsltlife
xsltlife

Reputation: 163

How get first String initial and other Strings as it is

I want yo get the first name initial and last name.

Input :

<root>
  <ele name="Samp Huwani"/>
  <ele name="Laura McKay (J)"/>
  <ele name="Dery Wertnu"/>
</root>

Output

<names>S Huwani</name>
<names>L McKay (J)</name>
<names>D Wertnu</name>

Tried Code:

<xsl:template match="root/ele">
  <names>
    <xsl:value-of select="replace(@name, '^(.{1}).* (.*)', '$1 $2')" />
  </name>
</xsl:template>

Result I am getting:

<names>S Huwani</name>
<names>L (J)</name>
<names>D Wertnu</name>

According to my code, I am getting L (J). it should be L McKay (J). But Other two results are working as expected

I am using XSLT 2.0. Thank you

Upvotes: 1

Views: 44

Answers (2)

michael.hor257k
michael.hor257k

Reputation: 117073

If you want to use regex for this, try:

<xsl:value-of select="replace(@name, '^(.{1})[^ ]* (.*)', '$1 $2')" />

Upvotes: 1

Sam
Sam

Reputation: 841

You can use substring and substring-after:

    <?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="2.0">
    <xsl:template match="root/ele">
        <names>
            <xsl:value-of select="concat(substring(@name, 1, 1), ' ', substring-after(@name, ' '))"/>
         </names>
    </xsl:template>
</xsl:stylesheet>

Upvotes: 1

Related Questions