Mongodb dynamic like operator - javascript

In mongodb the equivalent to sql "like" operator is
db.users.find({"shows": /m/})
Using nodejs/javascript I want to dynamically change letter, based on url paramater.
I have tried
letter = req.params.letter;
db.users.find({"shows": '/' + letter + '/'})
This doesn't work, I guess because the slashes are now strings are interpreted differently.

One way to do it, according to the documentation page:
db.users.find( { shows : { $regex : letter } } );

+1 for mindandmedia on the syntax. However, please remember, that if you want the query to use an index efficiently, you have to use prefix queries (also called rooted regexps) like /^prefix/
Your query is likely to be horribly slow otherwise - see the note in the docs here:
http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-RegularExpressions

You can try this:
let filter = "Dynamic";
let str = /.*Raj.*/;
console.log(str);
console.log(typeof(str));
let stra = eval(`/.*${filter}+.*/`);
console.log(stra);
console.log(typeof(stra));

Related

How to redirect url based on only one part of the path?

Let me explain what I mean:
I want to redirect from https://example.net/category/83745/my-first-post to https://myredirect.net/my-first-post but without considering /category/numbers/
For the moment I work with this:
if(window.location.pathname == '/category/83745/my-first-post')
{
window.location.href="https://myredirect.net/my-first-post";
}
And it is working fine but as I described I need to remove /category/numbers/ because they could be different and only consider this part /my-first-post for the redirection.
Thanks in advance.
if you want to just ignore the first 2 parts dynamically and only care about the last part of the URL then just do the following:
var stringContains = function (str, partial){
return (str.indexOf(partial) > -1);
};
var url = '/category/83745/my-first-post';
if(stringContains(url, "/category")){
var parts = a.split("/");
window.location.href = parts[parts.length-1];
}
You can use String's methods lastIndexOf and slice:
var path = window.location.pathname;
window.location.href = "https://myredirect.net" + path.slice(path.lastIndexOf('/') + 1);
Use Regex. Something like
if(window.location.pathname.match(/\/category\/\d+\/my\-first\-post$/)
{
window.location.href="https://myredirect.net/my-first-post";
}
You can run a regular expression match on the pathname
if(window.location.pathname.match(/my-first-post$/)) {
window.location.href='/my-first-post';
}
More on regexes: https://www.regular-expressions.info/
Another good tool for building and testing regexes: https://regex101.com/
Edit:
To give an example of how to regex according to the more fleshed out specs from Chris G
let pathmatch = window.location.pathname.match(/([^\/]+)$/g);
window.location.href = '/' + pathmatch[0];
Thus, regex can be utilized to grab any pattern and use it later.
IF there is a need to make sure the pathname contains category and/or numbers, it is easily added in to the pattern. This one simply disregards anything before the last forward slash (/)

Javascript: given an array of variables, function to remove characters and output another array

so I am still learning Javascript, so I know this is a basic questions, and I'd really like to learn what I'm missing. I have an array of variables, and I need a function that removes special characters, and returns the result as an array.
Here's my code:
var myArray = [what_hap, desc_injury];
function ds (string) {
string.replace(/[\\]/g, ' ')
string.replace(/[\"]/g, ' ')
string.replace(/[\/]/g, '-')
string.replace(/[\b]/g, ' ')
string.replace(/[\f]/g, ' ')
string.replace(/[\n]/g, ',')
string.replace(/[\r]/g, ' ')
string.replace(/[\t]/g, ' ');
return string;
}
ds (myArray);
I know that's not going to work, so I'm just trying to learn the simplest and cleanest way to output:
[whatHap: TEXTw/oSpecialCharacters, descInj: TEXTw/oSpecialCharacters]
Anyone willing to guide a noobie? Thanks! :)
The comments on the question are correct, you need to specify what you are asking a little better but I will try and give you some guidance from what I assume about your intended result.
One important thing to note which would fix the function you already have is that string.replace() will not change the string itself, it returns a new string with the replacements as you can see in the documentation. to do many replacements you need to do string = string.replace('a', '-')
On to a solution for the whole array. There are a couple ways to process an array in javascript: for loop, Array.forEach(), or Array.map(). I urge you to read the documentation of each and look up examples on your own to understand each and where they are most useful.
Since you want to replace everything in your array I suggest using .map()
or .foreach() since these will loop through the whole array for you without you having to keep track of the index yourself. Below are examples of using each to implement what I think you are going for.
Map
function removeSpecial(str) {
// replace all these character with ' '
// \ " \b \f \r \t
str = str.replace(/[\\"\b\f\r\t]/g, ' ');
// replace / with -
str = str.replace(/\//g, '-');
// replace \n with ,
str = str.replace(/\n/g, ',');
return str;
}
let myArray = ["string\\other", "test/path"];
let withoutSpecial = myArray.map(removeSpecial); // ["string other", "test-path"]
forEach
function removeSpecial(myArray) {
let withoutSpecial = [];
myArray.forEach(function(str) {
str = str.replace(/[\\"\b\f\r\t]/g, ' ');
// replace / with -
str = str.replace(/\//g, '-');
// replace \n with ,
str = str.replace(/\n/g, ',');
withoutSpecial.push(str)
});
return withoutSpecial;
}
let myArray = ["string\\other", "test/path"];
let withoutSpecial = removeSpecial(myArray); // ["string other", "test-path"]
The internalals of each function's can be whatever replacements you need it to be or you could replace them with the function you already have. Map is stronger in this situation because it will replace the values in the array, it's used to map the existing values to new corresponding values one to one for every element. On the other hand the forEach solution requires you to create and add elements to a new array, this is better for when you need to do something outside the array itself for every element in the array.
PS. you should check out https://regex101.com/ for help building regular expressions if you want a more complex replacements but you dont really need them for this situation
I realize that the way I wrote my goal isn't exactly clear. I think what I should have said was that given several text strings, I want to strip out some specific characters (quotes, for example), and then output each of those into an array that can be accessed. I have read about arrays, it's just been my experience in learning JS that reading code and actually doing code are two very different things.
So I appreciate the references to documentation, what I really needed to see was a real life example code.
I ended up finding a solution that works:
function escapeData(data) {
return data
.replace(/\r/g, "");
}
var result = {};
result.what_hap_escaped = escapeData($what_hap);
result.desc_injury_escaped = escapeData($desc_injury);
result;
I appreciate everyone's time, and hope I didn't annoy you guys too much with my poorly constructed question :)

Using Jquery to get numeric value which is in between "/" in link

I am trying to fetch numeric value from link like this.
Example link
/produkt/114664/bergans-of-norway-airojohka-jakke-herre
So I need to fetch 114664.
I have used following jquery code
jQuery(document).ready(function($) {
var outputv = $('.-thumbnail a').map(function() {
return this.href.replace(/[^\d]/g, '');
}).get();
console.log( outputv );
});
https://jsfiddle.net/a2qL5oyp/1/
The issue I am facing is that in some cases I have urls like this
/produkt/114664/bergans-of-norway-3airojohka-3jakke-herre
Here I have "3" inside text string, so in my code I am actually getting the output as "11466433" But I only need 114664
So is there any possibility i can get numeric values only after /produkt/ ?
If you know that the path structure of your link will always be like in your question, it's safe to do this:
var path = '/produkt/114664/bergans-of-norway-airojohka-jakke-herre';
var id = path.split('/')[2];
This splits the string up by '/' into an array, where you can easily reference your desired value from there.
If you want the numerical part after /produkt/ (without limitiation where that might be...) use a regular expression, match against the string:
var str = '/produkt/114664/bergans-of-norway-3airojohka-3jakke-herre';
alert(str.match(/\/produkt\/(\d+)/)[1])
(Note: In the real code you need to make sure .match() returned a valid array before accessing [1])

how to get the base url using regex in javascript

My app is going to work in multiple env, in which i need to get the common value (base url for my app) to work across..
from my window location how to i get certain part from the start..
example :
http://xxxxx.yyyy.xxxxx.com:14567/yx/someother/foldername/index.html
how can i get only:
http://xxxxx.yyyy.xxxxx.com:14567/yx/
my try :
var base = \w([yx]/)
the base only select yx/ how to get the value in front of this?
this part..
thanks in advance..
If 'someother' is known to be the root of your site, then replace
\w([yx]/)
with
(.*\/)someother\/
(note that the / characters are escaped here) which gives a first match of:
http://xxxxx.yyyy.xxxxx.com:14567/yx/
However, a regular expression may not be the best way of doing this; see if there's any way you can pass the base URL in by another manner, for example from the code running behind the page.
If you don't mind disregarding the trailing slash, you can do it without a regex:
var url = 'http://xxxxx.yyyy.xxxxx.com:14567/yx/someother/foldername/index.html';
url.split('/', 4).join('/');
//-> "http://xxxxx.yyyy.xxxxx.com:14567/yx"
If you want the trailing slash, it's easy to append with + '/'.
Please try following regexp:
http\:\/\/[\w\.]+\:\d+\/\w+\/
This one should do pretty well
http:\/\/[\w\.]+\:\d+\/\w+\/
Perhaps something like this?
Javascript
function myBase(url, baseString) {
if (url && baseString) {
var array = url.split(new RegExp("\\b" + baseString + "\\b"));
if (array.length === 2) {
return array[0] + baseString + "/";
}
}
return null;
}
var testUrl = "http://xxxxx.yyyy.xxxxx.com:14567/yx/someother/foldername/index.html",
testBase = "yx";
console.log(myBase(testUrl, testBase))
;
Output
http://xxxxx.yyyy.xxxxx.com:14567/yx/
On jsfiddle

Using javascript regex to translate a html

I would like to build my own translation function in javascript.
I already have a function language.lookup(key) which translates a word or expression:
var frenchHello = language.lookup('hello') //'bonjour'
Now I would like to write a function which takes a html string and translates it with my lookup function. In the html string I will have a special syntax for example #[translationkey] that will point out that this word should be translated.
This is the result I want:
var html = '<div><span>#[hello]</span><span>#[sir]</span>'
language.translate(html) //'<div><span>bonjour</span><span>monsieur</span>
How would I write language.translate?
My idea is to filter out my special syntax with regex and then run language.lookup on each key. Maybe with string replace or something.
I suck when it comes to regex and I've only come up with a very incomplete example but I include it anyway so maybe someone get the idea of what I am trying to do. Then if there is a better but complete different solution that is more than welcome.
var value = "#[hello], nice to see you.";
lookup = function(word){
return "bonjour";
};
var res = new RegExp( "\\b(hello)\\b", "gi" ).exec(value)
for (var c1 = 0; c1 < res.length; c1++){
value = value.replace(res[c1], lookup(res[c1]))
}
alert(value) //#[bonjour], nice to see you.
The regex should of course not filter out the word hello but the syntax and then collect the key by grouping or similar.
Can anyone help?
Just use String.replace method's ability to call function specified as second argument to generate replacement text and make a global replace using regexp matching your syntax:
var value = "#[hello], #[sir], nice to see you.";
lookup = function(full_match, word){
if(word == 'hello')
return "bonjour";
if(word == 'sir')
return "monsieur"
};
console.log(value.replace(/#\[(.+?)\]/gi, lookup))
Result:
bonjour, monsieur, nice to see you.
Of course when your replacement list gets bigger, you'd better use lookup object instead of series of ifs in lookup function, but you can really do whatever you want there.
You can try this to find all occurrences:
var re = new RegExp('#\\[([^\\]]+?)\\]', 'gi'),
str = '#[value1] plain text #[value2]',
match;
while (match = re.exec(str)) {
console.log(match);
}
You could use something like:
#\\[[^\\]]*\\]
Which matches the hash followed by an opening square bracket followed by zero or more characters NOT including the closing square bracket, followed by a closed square bracket.
Alternatively, perhaps it would be better to handle the translation at the server side (maybe even through your template engine) and send back to your client the translated response. Otherwise, (depending on the specific problem you are dealing with of course), you might end up sending a lot of data to the browser which might make your application respond slowly.
EDIT:
Here is a working piece of code:
var q="This #[ANIMAL1] was eaten by that #[ANIMAL2]";
var u = {"#[ANIMAL1]":"Lion","#[ANIMAL2]":"Frog"};
function insertAnimal(aString, lookup){
var res = (new RegExp("#\\[[^\\]]*\\]", "gi"))
while (m = res.exec(aString)){
aString = aString.replace(m, lookup[m])
}
return aString;
}
function main(){
alert(insertAnimal(q,u));
}
You can call the "main()" from an HTML document's body onload event
I can compare your requirement to 'resolving template texts within content'. If it is feasible to use Jquery , you should try Handlebars.js
.

Categories