使用 lodash 链接进行字符串操作
String manipulation using lodash chaining
我要更改字符串"Showing 8,868 research papers in XXX Journal; published between 2000-01-01 and 2015-06-31"
致:
New research papers in XXX Journal; published from 2001-01-01 onward
我想出了以下使用 lodash 的代码:
var desc = _.chain($('.description').text())
.thru(function (text) { return text.replace(/\s+/g, ' ') })
.thru(function (text) { return text.replace(/Showing\s[\d+\,*]+/, 'New') })
.split(';')
.map(function (phrase) {return phrase.replace('between', 'from').replace(/and\s[\d+-.]+/, 'onward') })
.join(';')
.value()
但我总是Uncaught TypeError: undefined is not a function
在线.thru(function (text) { return text.replace(/\s+/g, ' ') })
我做错了什么?
可能您使用的是过时版本的 lodash,因为您的代码适用于 lodash 3.9.3。请注意 _.thru
未在 lodash 2 中实现。*
与您的 TypeError
无关,您可以使用 method() and flow() 使代码更小:
function replace(a, b) { return _.method('replace', a, b); }
_($('.description').text())
.chain()
.thru(replace(/\s+/g, ' '))
.thru(replace(/Showing\s[\d+\,*]+/, 'New'))
.split(';')
.map(_.flow(replace('between', 'from'), replace(/and\s[\d+-.]+/, 'onward')))
.join(';')
.value()
我要更改字符串"Showing 8,868 research papers in XXX Journal; published between 2000-01-01 and 2015-06-31"
致:
New research papers in XXX Journal; published from 2001-01-01 onward
我想出了以下使用 lodash 的代码:
var desc = _.chain($('.description').text())
.thru(function (text) { return text.replace(/\s+/g, ' ') })
.thru(function (text) { return text.replace(/Showing\s[\d+\,*]+/, 'New') })
.split(';')
.map(function (phrase) {return phrase.replace('between', 'from').replace(/and\s[\d+-.]+/, 'onward') })
.join(';')
.value()
但我总是Uncaught TypeError: undefined is not a function
在线.thru(function (text) { return text.replace(/\s+/g, ' ') })
我做错了什么?
可能您使用的是过时版本的 lodash,因为您的代码适用于 lodash 3.9.3。请注意 _.thru
未在 lodash 2 中实现。*
与您的 TypeError
无关,您可以使用 method() and flow() 使代码更小:
function replace(a, b) { return _.method('replace', a, b); }
_($('.description').text())
.chain()
.thru(replace(/\s+/g, ' '))
.thru(replace(/Showing\s[\d+\,*]+/, 'New'))
.split(';')
.map(_.flow(replace('between', 'from'), replace(/and\s[\d+-.]+/, 'onward')))
.join(';')
.value()