Skip to content

Commit

Permalink
improvement normalize-space function #32
Browse files Browse the repository at this point in the history
  • Loading branch information
zhengchun committed Jan 29, 2019
1 parent 4bbdf6d commit c8489ed
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 4 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -160,5 +160,8 @@ Supported Features
Changelogs
===

2019-01-29
- improvement `normalize-space` function. [#32](https://github.com/antchfx/xpath/issues/32)

2018-12-07
- supports XPath 2.0 Sequence expressions. [#30](https://github.com/antchfx/xpath/pull/30) by [@minherz](https://github.com/minherz).
13 changes: 11 additions & 2 deletions func.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"errors"
"fmt"
"math"
"regexp"
"strconv"
"strings"
)
Expand Down Expand Up @@ -308,6 +309,11 @@ func containsFunc(arg1, arg2 query) func(query, iterator) interface{} {
}
}

var (
regnewline = regexp.MustCompile(`[\r\n\t]`)
regseqspace = regexp.MustCompile(`\s{2,}`)
)

// normalizespaceFunc is XPath functions normalize-space(string?)
func normalizespaceFunc(q query, t iterator) interface{} {
var m string
Expand All @@ -317,11 +323,14 @@ func normalizespaceFunc(q query, t iterator) interface{} {
case query:
node := typ.Select(t)
if node == nil {
return false
return ""
}
m = node.Value()
}
return strings.TrimSpace(m)
m = strings.TrimSpace(m)
m = regnewline.ReplaceAllString(m, " ")
m = regseqspace.ReplaceAllString(m, " ")
return m
}

// substringFunc is XPath functions substring function returns a part of a given string.
Expand Down
6 changes: 4 additions & 2 deletions xpath_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -650,7 +650,9 @@ func example() *TNode {
<meta name="language" content="en"/>
</head>
<body>
<h1> This is a H1 </h1>
<h1>
This is a H1
</h1>
<ul>
<li><a id="1" href="/">Home</a></li>
<li><a id="2" href="/about">about</a></li>
Expand Down Expand Up @@ -678,7 +680,7 @@ func example() *TNode {
// The HTML body section.
body := xhtml.createChildNode("body", ElementNode)
n = body.createChildNode("h1", ElementNode)
n = n.createChildNode(" This is a H1 ", TextNode)
n = n.createChildNode("\nThis is a H1\n", TextNode)
ul := body.createChildNode("ul", ElementNode)
n = ul.createChildNode("li", ElementNode)
n = n.createChildNode("a", ElementNode)
Expand Down

0 comments on commit c8489ed

Please sign in to comment.