Javascript Regular Expression with multiple conditions - javascript

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 ?

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;
}

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;
}

Related

How to extract an ext from a filename having special chars in it-javascript

I am trying to get a the extension from a filename. The filename could include special characters, "#,#,.,_,(),..etc)
ex:
var file1 = "fake.der"
var file2 = "fake.1.der"
var file3 = "fake_test.3.der"
NOw In the above case I want to extract only the ext "der" from every filename.
I tried:
file1.split(".")[1] //works fine
file2.split(".")[1] // gives me 1 -incorrect but file2.split(".")[2] gives correct result
file3.split(".")[1] //gives 3-incorrect.
since filename could vary, I dont kinda want to make it the .split(".")[1] static, by changing it to .split(".")[2] for other filenames and so on..
HOw can I make sure that regardless of how many dots present in the filename, I'll always get the extension only as o/p, is there a better appraoch?
Thanks!
Use a regular expression to match a dot, followed by non-dot characters, followed by the end of the string:
function getExt(str) {
const match = str.match(/\.([^.]+)$/);
if (match) {
return match[1];
} else {
return 'Not found';
}
}
var file1 = "fake.der";
var file2 = "fake.1.der";
var file3 = "fake_test.3.der";
var file4 = "foobar";
[file1, file2, file3, file4].forEach(str => console.log(getExt(str)));
Note that you can't always be sure that an input string contains a well-formatted file extension, so make sure to handle those unexpected cases, as done above.
With lastIndexOf:
function getExtension(file) {
const index = file.lastIndexOf('.');
return index === -1 ? '' : file.slice(index + 1);
}
This also handles the case if the string does not contain a ..
you can use the \w in a regular expression which matches any "word" character. A "word" character is any letter or digit or the underscore character. You should use $ which starts marching from the back of the string
function ext(path) {
let extension = path.match(/\w+$/)
return extension ? extension[0].replace(".","") : null;
}
Just use .split() and some length calculations:
var file1 = "fake.der";
var file2 = "fake.1.der";
var file3 = "fake_test.3.der";
function getExtension(name) {
var nameArr = name.split(".");
var fileExt = nameArr[nameArr.length - 1];
return fileExt;
}
console.log(getExtension(file1));
console.log(getExtension(file2));
console.log(getExtension(file3));
Use slice ;)
const fileName = "file.name.extension.der";
console.log(fileName.split('.').slice(-1));

I need a help for regexp in javascript code

var str = "^" + "/post/\d+" + "$";
var regex = new RegExp(str);
var flag = regex.test("/post/3333");
console.log(flag) // -> false
console.log(regex) // -> /^\/post\/d+$/
I'm expecting the result becomes true, but it results in false.
I think the problem is "\" is added automatically before "/" when RegExp instance is created.
How am I supposed to write in order to make it work?
You don't need the new RegExp constructor and string
Here example
var regex = /post\/\d+$/;
var flag = regex.test("/post/3333");
I removed ^ flag, because regex will not work with this format of input "website/post/3333"
Here's a more specific regular expression to match the format of /post/####:
var regex = /\/post\/[0-9]+$/;
var flag = regex.test("/post/3333");
This will test for the string /post/ followed by one or more digits, occurring at the end of the line.
Likewise:
var regex = /\/post\/[0-9]{4}$/;
var flag = regex.test("/post/3333");
will test for the string /post/ followed by 4 digits, occurring at the end of the line.

Use dynamic (variable) string as regex pattern in JavaScript

I want to add a (variable) tag to values with regex, the pattern works fine with PHP but I have troubles implementing it into JavaScript.
The pattern is (value is the variable):
/(?!(?:[^<]+>|[^>]+<\/a>))\b(value)\b/is
I escaped the backslashes:
var str = $("#div").html();
var regex = "/(?!(?:[^<]+>|[^>]+<\\/a>))\\b(" + value + ")\\b/is";
$("#div").html(str.replace(regex, "" + value + ""));
But this seem not to be right, I logged the pattern and its exactly what it should be.
Any ideas?
To create the regex from a string, you have to use JavaScript's RegExp object.
If you also want to match/replace more than one time, then you must add the g (global match) flag. Here's an example:
var stringToGoIntoTheRegex = "abc";
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;
var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.
JSFiddle demo here.
In the general case, escape the string before using as regex:
Not every string is a valid regex, though: there are some speciall characters, like ( or [. To work around this issue, simply escape the string before turning it into a regex. A utility function for that goes in the sample below:
function escapeRegExp(stringToGoIntoTheRegex) {
return stringToGoIntoTheRegex.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
var stringToGoIntoTheRegex = escapeRegExp("abc"); // this is the only change from above
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;
var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.
JSFiddle demo here.
Note: the regex in the question uses the s modifier, which didn't exist at the time of the question, but does exist -- a s (dotall) flag/modifier in JavaScript -- today.
If you are trying to use a variable value in the expression, you must use the RegExp "constructor".
var regex = "(?!(?:[^<]+>|[^>]+<\/a>))\b(" + value + ")\b";
new RegExp(regex, "is")
I found I had to double slash the \b to get it working. For example to remove "1x" words from a string using a variable, I needed to use:
str = "1x";
var regex = new RegExp("\\b"+str+"\\b","g"); // same as inv.replace(/\b1x\b/g, "")
inv=inv.replace(regex, "");
You don't need the " to define a regular expression so just:
var regex = /(?!(?:[^<]+>|[^>]+<\/a>))\b(value)\b/is; // this is valid syntax
If value is a variable and you want a dynamic regular expression then you can't use this notation; use the alternative notation.
String.replace also accepts strings as input, so you can do "fox".replace("fox", "bear");
Alternative:
var regex = new RegExp("/(?!(?:[^<]+>|[^>]+<\/a>))\b(value)\b/", "is");
var regex = new RegExp("/(?!(?:[^<]+>|[^>]+<\/a>))\b(" + value + ")\b/", "is");
var regex = new RegExp("/(?!(?:[^<]+>|[^>]+<\/a>))\b(.*?)\b/", "is");
Keep in mind that if value contains regular expressions characters like (, [ and ? you will need to escape them.
I found this thread useful - so I thought I would add the answer to my own problem.
I wanted to edit a database configuration file (datastax cassandra) from a node application in javascript and for one of the settings in the file I needed to match on a string and then replace the line following it.
This was my solution.
dse_cassandra_yaml='/etc/dse/cassandra/cassandra.yaml'
// a) find the searchString and grab all text on the following line to it
// b) replace all next line text with a newString supplied to function
// note - leaves searchString text untouched
function replaceStringNextLine(file, searchString, newString) {
fs.readFile(file, 'utf-8', function(err, data){
if (err) throw err;
// need to use double escape '\\' when putting regex in strings !
var re = "\\s+(\\-\\s(.*)?)(?:\\s|$)";
var myRegExp = new RegExp(searchString + re, "g");
var match = myRegExp.exec(data);
var replaceThis = match[1];
var writeString = data.replace(replaceThis, newString);
fs.writeFile(file, writeString, 'utf-8', function (err) {
if (err) throw err;
console.log(file + ' updated');
});
});
}
searchString = "data_file_directories:"
newString = "- /mnt/cassandra/data"
replaceStringNextLine(dse_cassandra_yaml, searchString, newString );
After running, it will change the existing data directory setting to the new one:
config file before:
data_file_directories:
- /var/lib/cassandra/data
config file after:
data_file_directories:
- /mnt/cassandra/data
Much easier way: use template literals.
var variable = 'foo'
var expression = `.*${variable}.*`
var re = new RegExp(expression, 'g')
re.test('fdjklsffoodjkslfd') // true
re.test('fdjklsfdjkslfd') // false
Using string variable(s) content as part of a more complex composed regex expression (es6|ts)
This example will replace all urls using my-domain.com to my-other-domain (both are variables).
You can do dynamic regexs by combining string values and other regex expressions within a raw string template. Using String.raw will prevent javascript from escaping any character within your string values.
// Strings with some data
const domainStr = 'my-domain.com'
const newDomain = 'my-other-domain.com'
// Make sure your string is regex friendly
// This will replace dots for '\'.
const regexUrl = /\./gm;
const substr = `\\\.`;
const domain = domainStr.replace(regexUrl, substr);
// domain is a regex friendly string: 'my-domain\.com'
console.log('Regex expresion for domain', domain)
// HERE!!! You can 'assemble a complex regex using string pieces.
const re = new RegExp( String.raw `([\'|\"]https:\/\/)(${domain})(\S+[\'|\"])`, 'gm');
// now I'll use the regex expression groups to replace the domain
const domainSubst = `$1${newDomain}$3`;
// const page contains all the html text
const result = page.replace(re, domainSubst);
note: Don't forget to use regex101.com to create, test and export REGEX code.
var string = "Hi welcome to stack overflow"
var toSearch = "stack"
//case insensitive search
var result = string.search(new RegExp(toSearch, "i")) > 0 ? 'Matched' : 'notMatched'
https://jsfiddle.net/9f0mb6Lz/
Hope this helps

I need to match a certain part of url path using Regex and Javascript

I have the following link:
sitename.com/Default.aspx?PageID=13078494
I want to grab the following: "PageID=13078494". This is what I have so far:
var url = "sitename.com/Default.aspx?PageID=13078494";
urlmatch = url.match([PageID=13078494]);
urlmatch[0];
Is this the proper expression for what I'm trying to do?
Your regex and its syntax are wrong.
A better way would be to not use a regex at all. Use .split() instead:
var urlmatch = url.split('?')[1];
Here's the fiddle: http://jsfiddle.net/qpXNU/
var myregexp = /[?&]PageID=(\d+)/i;
var match = myregexp.exec(url);
if (match != null) {
//This is if your match it successful
result = match[1];
} else {
//This is if url doesn't match
result = "";
}
This one will work regardless of where PageID is. It will match
sitename.com/Default.aspx?PageID=13078494
anything.org/Default.aspx?PageID=13078494
sitename.com/Default.aspx?foo=bar&PageID=13078494
sitename.com/Default.html?foo=bar&PageID=13078494&bar=foo
Default.html?foo=bar&PageID=13078494&bar=foo
Importantly, it WON'T match
sitename.com/Default.aspx?NotThePageID=13078494
Or without the checking, simply
url.match(/[?&]PageID=(\d+)/i)[1], but I'd advice against that unless your SURE it will always match.
Try the following regex, which will extract the PageID and place it in the first match group:
var url = "sitename.com/Default.aspx?PageID=13078494";
urlmatch = url.match(/PageID=(\d+)/);
alert(urlmatch[1]);​ // 13078494
If you are matching specific value, then it's fine, otherwise use below to match any number of digits in pageID:
/PageID=\d+/
as:
var url = "sitename.com/Default.aspx?PageID=13078494";
var urlmatch = url.match(/PageID=\d+/);
alert(urlmatch[0]);
or to match 8 exact digits in pageID, use:
/PageID=\d{8}/
as:
var url = "sitename.com/Default.aspx?PageID=13078494";
var urlmatch = url.match(/PageID=\d{8}/);
alert(urlmatch[0]);
When it comes to handling URLs, the browser is pretty good.
You should convert your string to an actual URL like so:
var toURL = function (href) {
var a = document.createElement('a');
a.href = href;
return a;
};
Now use the browser's built-in parsing capabilities:
var url = toURL('sitename.com/Default.aspx?PageID=13078494');
alert(url.search);

Why does this jQuery code not work?

Why doesn't the following jQuery code work?
$(function() {
var regex = /\?fb=[0-9]+/g;
var input = window.location.href;
var scrape = input.match(regex); // returns ?fb=4
var numeral = /\?fb=/g;
scrape.replace(numeral,'');
alert(scrape); // Should alert the number?
});
Basically I have a link like this:
http://foo.com/?fb=4
How do I first locate the ?fb=4 and then retrieve the number only?
Consider using the following code instead:
$(function() {
var matches = window.location.href.match(/\?fb=([0-9]+)/i);
if (matches) {
var number = matches[1];
alert(number); // will alert 4!
}
});
Test an example of it here: http://jsfiddle.net/GLAXS/
The regular expression is only slightly modified from what you provided. The global flag was removed, as you're not going to have multiple fb='s to match (otherwise your URL will be invalid!). The case insensitive flag flag was added to match FB= as well as fb=.
The number is wrapped in curly brackets to denote a capturing group which is the magic which allows us to use match.
If match matches the regular expression we specify, it'll return the matched string in the first array element. The remaining elements contain the value of each capturing group we define.
In our running example, the string "?fb=4" is matched and so is the first value of the returned array. The only capturing group we have defined is the number matcher; which is why 4 is contained in the second element.
If you all you need is to grab the value of fb, just use capturing parenthesis:
var regex = /\?fb=([0-9]+)/g;
var input = window.location.href;
var tokens = regex.exec(input);
if (tokens) { // there's a match
alert(tokens[1]); // grab first captured token
}
So, you want to feed a querystring and then get its value based on parameters?
I had had half a mind to offer Get query string values in JavaScript.
But then I saw a small kid abusing a much respectful Stack Overflow answer.
// Revised, cooler.
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)')
.exec(window.location.search);
return match ?
decodeURIComponent(match[1].replace(/\+/g, ' '))
: null;
}
And while you are at it, just call the function like this.
getParameterByName("fb")
How about using the following function to read the query string parameter in JavaScript:
function getQuerystring(key, default_) {
if (default_==null)
default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}
and then:
alert(getQuerystring('fb'));
If you are new to Regex, why not try Program that illustrates the ins and outs of Regular Expressions

Categories