使用lodash链的字符串操作

String manipulation using lodash chaining

本文关键字:字符串 操作 lodash 使用      更新时间:2023-09-26

我想改变字符串"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()和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()