Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String manipulation using lodash chaining

I want to change the string "Showing 8,868 research papers in XXX Journal; published between 2000-01-01 and 2015-06-31"

to: New research papers in XXX Journal; published from 2001-01-01 onward

I came up with the following code that uses 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()

But I always get Uncaught TypeError: undefined is not a function on the line .thru(function (text) { return text.replace(/\s+/g, ' ') })

What am I doing wrong?

like image 252
bard Avatar asked Aug 04 '26 08:08

bard


2 Answers

Probably you use outdated version of lodash, since your code works with lodash 3.9.3. Note that _.thru is not implemented in lodash 2.*

like image 96
Magomogo Avatar answered Aug 06 '26 22:08

Magomogo


Unrelated to your TypeError, you could use method() and flow() to make your code a lot smaller:

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()
like image 40
Adam Boduch Avatar answered Aug 06 '26 21:08

Adam Boduch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!