Quesofat
Quesofat

Reputation: 1531

URL Param rewrite in node express

Whenever a tag is submitted with spaces, the spaces show up as %20 in the response. How would I rewrite each space so in either the request and response it can be a dash? Are there any reliable library's for this? Thanks!

Route

 router.get('/search/:tag', function(req, res) {
      const tag = req.params.tag;
      tag.toLowerCase();
      shopify.article.list(86289414)
      .then(function (response) {
        response.reverse();

        response = response.map(function(element) {
            return {
              author: element.author,
              blog_id: element.blog_id,
              body_html: element.body_html,
              created_at: element.created_at,
              handle: element.handle,
              id: element.id,
              image: element.image,
              published_at: element.published_at,
              summary_html: element.summary_html,
              tags: element.tags.toString().toLowerCase(),
              template_suffix: element.template_suffix,
              title: element.title,
              updated_at: element.updated_at,
              user_id: element.user_id
            }
        })


        response = response.filter(function(item) {
         return item.tags.indexOf(tag) > -1;
       });

        var data = {
          articles: response.map((article) => {
            return {
              author: article.author,
              id: article.id,
              html: article.body_html,
              tags: article.tags.split(","),
              date: moment(article.published_at).format("Do MMM YYYY"),
              slug: article.handle,
              title: article.title,
            } // return
          }) // map
        } // data

          console.log(data);
          res.render('blog-tags' , data);

      }) // then
        .catch(err => console.log(err) )
    });

Upvotes: 1

Views: 272

Answers (1)

rsp
rsp

Reputation: 111374

First of all this will not do what you expect:

tag.toLowerCase();

You need to use:

tag = tag.toLowerCase();

if you want the value in the tag variable to change.

That is because strings in JavaScript are immutable and no operation can change a string, you can only replace the values of variables with new strings. And methods like .toLowerCase() always return a new string.

Now, if your variable already contains '%20' etc. then you need to use:

tag = decodeURIComponent(tag);

but note that this is likely to already be handled by the framework.

Now, to change spaces to underscores, use:

tag = tag.replace(/ /g, '_');

You can combine all of that as:

tag = decodeURIComponent(tag).toLowerCase().replace(/ /g, '_');

Or this if your variable already contains decoded string:

tag = tag.toLowerCase().replace(/ /g, '_');

Example:

let tag = 'Aaa%20BbB%20cCC';
tag = decodeURIComponent(tag).toLowerCase().replace(/ /g, '_');
console.log(tag);
// prints: aaa_bbb_ccc

Upvotes: 1

Related Questions