Extracting text between paragraph tag in a Jade view

Problem

I try to extract text between paragraph tag in a Jade view but it doesn't work.

My subject:

<p> My content. </p> <img src="https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcTJ9ylGJ4SDyl49VGh9Q9an2vruuMip-VIIEG38DgGM3GvxEi_H"> <p> Second sentence. </p>

Jade view:

- var content = post.content.slice('/<p>(.*?)<\/p>/g');
p #{content}

Result:

<
Problem courtesy of: tonymx227

Solution

why do u need to extract text between paragraph tag on server side??

that will be something we do on client side js


in your case, context should be a parameter you pass to jade view, by res.render('view', {context : "My content."}) or res.locals

so you can deal with your #{context} in Jade view

if you want to declare variable context in Jade view

it should be like

-var context= "My content."

p #{content}


reply to jsdom code

in your code

posts[i] is undefined.

I suppose u want to iterate posts, so you should use a iterator here

you can use async module here

in this case, map is very suitable

see here for document -> async map

Creation.findAll({where: "state = 1",order: 'id DESC', limit: 2}).success(function(creations) {
    Post.findAll({where: "state = 1",order: 'id DESC', limit: 2}).success(function(posts){

async.map(posts, function(postEntity, callback){
jsdom.env(
            postEntity.content,
            ["http://code.jquery.com/jquery.js"],
            function(errors, window) {
                //deal with errors
                if(errors) return callback(errors);

                postEntity.content = window.$("p").text();
                callback(null, postEntity);
            }
        );
}, function(err, transformedPosts){
    if(err) return callback(err);
    res.render('index', {
        creations: creations,
        posts: transformedPosts,
        title: "Anthony Cluse | Portfolio"
    });
});


});
});

FYI, you should use control flow library to manage your callback code

otherwise, it would be really hard to maintain

I recommend async

Solution courtesy of: williamC

Discussion

var i = 0;
Creation.findAll({where: "state = 1",order: 'id DESC', limit: 2}).success( function(creations) {
    Post.findAll({where: "state = 1",order: 'id DESC', limit: 2}).success(function(posts){
        console.log(posts[i].content);
        jsdom.env(
            posts[i].content,
            ["http://code.jquery.com/jquery.js"],
            function(errors, window) {
                posts[i].content = window.$("p").text();
            }
        );
        i++;
        res.render('index', {
            creations: creations,
            posts: posts,
            title: "Anthony Cluse | Portfolio"
        });
    });
});
Discussion courtesy of: tonymx227

This recipe can be found in it's original form on Stack Over Flow.