Javascript Regular Expression with multiple conditions

281 views Asked by At

I am using Nginx njs module for some url modifications.

My use case is to return the redirection uri for the given uri.

URI's will be as follows:

/books
/books/economic-genious
/books/flight-mechanics

My regular expression to match the above URI's as follows -

/books/(.*)|/books$

First part of expression /books/(.*) is to match below URI's:

/books/economic-genious
/books/flight-mechanics

Second part of expression /books$ is to match below URI's:

/books 

My destination is configured as follows: /ebooks/$1. So that the above URI's will be converted to:

/ebooks
/ebooks/economic-genious
/ebooks/flight-mechanics

Javascript code:

function getMappedURI(uri) {
    var exp = new RegExp('/books/(.*)|/books$');
    var destUri = '/ebooks/$1';
    var redirectUri = uri.replace(exp, destUri);
    return redirectUri;
}

Above code is working fine for the below URI's:

/books/economic-genious
/books/flight-mechanics

But for the URI /books, it should return /ebooks/. But it is appending some non printable special character at the end of /ebooks/.

I think it is trying to replace $1 with some special character.

How to avoid adding of special character at the end ?

2

There are 2 answers

6
GolamMazid Sajib On BEST ANSWER

Try with this regex: \/books(\/(.*))?$

Demo here...

code:

function getMappedURI(uri) {
    var exp = new RegExp('\/books(\/(.*))?$');
    var destUri = '/ebooks$1';
    var redirectUri = uri.replace(exp, destUri);
    return redirectUri;
}
3
vixalien On

The OR | operator only works in parens. So you should make the match to (/books/(.*)|/books$) and I don't think the $ word match because, for anything to be matched It should be in parens, too, making the new match URL: (/books/(.*)|/books). You'll then have to use $2 instead of $1 as substitute instead.

function getMappedURI(uri) {
    var exp = new RegExp('(/books/(.*)|/books)');
    var destUri = '/ebooks/$2';
    var redirectUri = uri.replace(exp, destUri);
    return redirectUri;
}

But, if you want to want everything from /books/foo to /ebooks/foo, use this instead: /books/(.*) with $1 as substitute.

function getMappedURI(uri) {
    var exp = new RegExp('/books/(.*)');
    var destUri = '/ebooks/$1';
    var redirectUri = uri.replace(exp, destUri);
    return redirectUri;
}