I have some strings like the following ones :
var resource1 = '/myapi/person/pascal/address/town';
var resource2 = '/myapi/person/john/address/town';
var resource3 = '/myapi/person/messi/address/town';
This is what I tried so far :
The pattern is :
var pattern = '/myapi/person/(.*)/address/town';
This is what I tried so far :
var resource1 = '/myapi/person/pascal/address/town';
var resource2 = '/myapi/person/john/address/town';
var resource3 = '/myapi/person/messi/address/town';
var pattern = '/myapi/person/(.*)/address/town';
var pattern = new RegExp(pattern);
if (pattern.test(resource1)){
console.log('yes');
}
Question
How can I dynamically use that pattern to check if resource1, resource2 or resource3 match that pattern?
Regards.
I suggest using stricter pattern. Use a negated character class instead of a greedy wildcard.
let resources = ['/myapi/person/pascal/address/town',
'/myapi/person/john/address/town',
'/myapi/person/messi/address/town'];
var regex = new RegExp('/myapi/person/([^/]+)/address/town');
for (var i = 0, len = resources.length; i < len; i++) {
if(regex.test(resources[i]))
console.log(`valid: ${resources[i]}`);
}
You have put a capture group around the person names variable. If you intend to capture those you can use .exec instead of .test:
let resources = ['/myapi/person/pascal/address/town',
'/myapi/person/john/address/town',
'/myapi/person/messi/address/town'];
var regex = new RegExp('/myapi/person/([^/]+)/address/town');
for (var i = 0, len = resources.length; i < len; i++) {
if ((m = regex.exec(resources[i])) !== null) {
console.log(m[1]);
}
}
The following regex should work:
/\/myapi\/person\/(.*)\/address\/town/
It can be used like so:
var string = '/myapi/person/pascal/address/town';
var re = /\/myapi\/person\/(.*)\/address\/town/;
re.test(string); //will return true
I encourage you to take a look it how it works here:
https://regexr.com/3ri4m
Related
I have 2 strings with some chars. One of them is with "mashed" characters, and the other one is with ordered characters which have some sense. For example:
wvEr2JmJUs2JRr:7Fob9WIB8mSOA?w0s2E:7-f/-G/N-.f7jN:Mi:.CDfGX7tn!
Identification: zpE?bkHlfYS-hIDate: 07/08/2057 12:34:56.789 CGT
So as you may see - the first one have equivalent of symbols which are the same for the equal symbol in the second one.
And the task is - to create somehow kind of alphabet from them, because I have third one string wich have to be "decoded". (wvEr2JmJUs2JRr:7a1AJvvHvAmRRWsxWsFAvJvAJAaoE88A2?s2AxJ1?290s2E:7-f/-G/N-.f7jN:MC:ifDCGN7tn!).
And the tricky part here is - that if I'm pretty sure for the first two strings that they're absolutely equal like a number of chars, so about the new one - is completely different number of symbols, but they consisting in the "alphabet"
And here is my current code for creation of the "alphabet":
var enc = "wvEr2JmJUs2JRr:7Fob9WIB8mSOA?w0s2E:7-f/-G/N-.f7jN:Mi:.CDfGX7tn!";
var dec = "Identification: zpE?bkHlfYS-hIDate: 07/08/2057 12:34:56.789 CGT";
var newenc = "wvEr2JmJUs2JRr:7a1AJvvHvAmRRWsxWsFAvJvAJAaoE88A2?s2AxJ1?290s2E:7-f/-G/N-.f7jN:MC:ifDCGN7tn!";
var myenc = {};
var mynewenc = {};
for (i = 0; i < enc.length; i+=1) {
var encoded = new Array(enc[i]);
var decoded = new Array(dec[i]);
myenc[enc[i]] = dec[i];
};
console.log(myenc);
And now - how I have to decode, the new one string, using this "alphabet"?
var enc = "wvEr2JmJUs2JRr:7Fob9WIB8mSOA?w0s2E:7-f/-G/N-.f7jN:Mi:.CDfGX7tn!";
var dec = "Identification: zpE?bkHlfYS-hIDate: 07/08/2057 12:34:56.789 CGT";
var newenc = "wvEr2JmJUs2JRr:7a1AJvvHvAmRRWsxWsFAvJvAJAaoE88A2?s2AxJ1?290s2E:7-f/-G/N-.f7jN:MC:ifDCGN7tn!";
function make_dictionary(enc, dec){
o = new Object();
if(enc.length == dec.length){
for(i=0; i<enc.length; i++){
o[enc[i]] = dec[i];
}
}
else{
console.log('error');
}
return o;
}
function translate(newenc, dictionary, fill){
var newstring = '';
for(i=0; i<newenc.length; i++){
if(typeof dictionary[newenc[i]] !== 'undefined'){
newstring += dictionary[newenc[i]];
}
else{
newstring += fill;
}
}
return newstring;
}
var d = make_dictionary(enc, dec);
console.log(d);
var string = translate(enc, d, '_');
console.log(string);
var string = translate(newenc, d, '_');
console.log(string);
Here's one way that you can approach it (as I understand the question):
// Create your dictionary
var dict = {};
var enc = "wvEr2JmJUs2JRr:7Fob9WIB8mSOA?w0s2E:7-f/-G/N-.f7jN:Mi:.CDfGX7tn!".split('');
var dec = "Identification: zpE?bkHlfYS-hIDate: 07/08/2057 12:34:56.789 CGT".split('');
// Populate your dictionary
for (var i = 0; i < enc.length; i++) {
dict[enc[i]] = dec[i];
}
// You can use your dictionary like this
var newenc = "wvEr2JmJUs2JRr:7a1AJvvHvAmRRWsxWsFAvJvAJAaoE88A2?s2AxJ1?290s2E:7-f/-G/N-.f7jN:MC:ifDCGN7tn!".split('');
// Returns your translated string
newenc.map(function(e) {
return dict[e];
}).join('');
However for this method you'll have to deal with characters that are defined in newenc that are not defined in your enc (such as T). I tried to do the best I could given the situation and rules that you've described, hope this helps!
If I understand well, you can try using this code.
It is finding the appropriate encoded letter in your enc variable and if the letter is found, it is replacing it with the corresponding letter from your dec variable.
var enc = "wvEr2JmJUs2JRr:7Fob9WIB8mSOA?w0s2E:7-f/-G/N-.f7jN:Mi:.CDfGX7tn!";
var dec = "Identification: zpE?bkHlfYS-hIDate: 07/08/2057 12:34:56.789 CGT";
var newenc = "wvEr2JmJUs2JRr:7a1AJvvHvAmRRWsxWsFAvJvAJAaoE88A2?s2AxJ1?290s2E:7-f/-G/N-.f7jN:MC:ifDCGN7tn!";
for (i = 0; i < newenc.length; i++) {
for (j = 0; j < enc.length; j++) {
if (enc[j] == newenc[i])
newenc[i] = dec[j];
}
};
console.log(newenc);
At the end your variable newenc may contain your decoded string.
How would you extract the URL parameters in javascript through a POST method?
For example:
localhost:8080/file.html/a/30/b/40
a and b would be keys while
30 and 40 would be the values for those keys
Thanks in advance!
Did you mean GET?
file.html?a=30&b=40
From this URL, you can get the parameters as follows:
var param = {};
var s = window.location.search.substring(1).split('&');
for (var i = 0; i < s.length; ++i) {
var parts = s[i].split('=');
param[parts[0]] = parts[1];
}
console.log(param);
EDIT:
The URL you provided doesn't have to do anything with POST, as far as I know, but if you can get it into a JavaScript variable, you can do this:
var url = "file.html/a/30/b/40";
var param = {};
var parts = url.split("/");
for (var i = 1; i < parts.length; i += 2) {
param[parts[i]] = parts[i+1];
}
console.log(param);
How about using a regular expression like this?
​var url = document.URL; // get the current URL
var matches = url.match(/.*\/a\/(\d+)\/b\/(\d+)/); // match it with a regex
var a = matches[1]; // the "a" number (as string)
var b = matches[2]; // the "b" number (as string)
Note that the match method returns a list, the first element of which is the overall match with the remaining items being the captured elements, i.e. the two (\d+) parts of the regex pattern. That's why this snippet uses matches[1] and matches[2] while ignoring matches[0].
I want to code a check for duplicate url's, but a simple string match will not work, e.g. string1 == string2. Consider the following url's as an example:
www.facebook.com/authorProfile
facebook.com/authorProfile
http://www.facebook.com/authorProfile
http://facebook.com/authorProfile
function extract(str){
var patterns = [
"http://www.",
"http://",
"www."
];
for(var i=0, len=patterns.length; i < len; i++){
var pattern = patterns[i];
if(str.indexOf(pattern) == 0)
return str.substring(pattern.length);
}
return str;
}
This will convert all those links to facebook.com/authorProfile style so you can compare them.
links = [
"www.facebook.com/authorProfile",
"facebook.com/authorProfile",
"http://www.facebook.com/authorProfile",
"http://facebook.com/authorProfile"
];
for(var i=0, len=links.length; i<len; i++){
console.log( extract(links[i]) );
}
// will produce 4 "facebook.com/authorProfile"
How about using javascript regex? Basically, remove http:// and www.
.replace(/www.|http:\/\//g, '');
Example:
var s1 = 'www.facebook.com/authorProfile';
var s2 = 'facebook.com/authorProfile';
var s3 = 'http://www.facebook.com/authorProfile';
var s4 = 'http://facebook.com/authorProfile';
s1.replace(/www.|http:\/\//g, '');
s2.replace(/www.|http:\/\//g, '');
s3.replace(/www.|http:\/\//g, '');
s4.replace(/www.|http:\/\//g, '');
All become:
facebook.com/authorProfile
I want to get the file endings from some files in a list.
File 1
File 2
File 3
File 4
Basically, the file endning could be anything, and the string can contain more than just one ".". So I need to fetch the ending only.
I want to get a result that looks like:
mp4
ogg
mp3
jpg
Thanks.
You can get the extensions for all links in a document like this:
var endings = [];
var links = document.getElementsByTagName("a");
var matches;
for (var i = 0; i < links.length; i++) {
if (links[i].href) {
matches = links[i].href.match(/\.([^\.]+)$/);
if (matches) {
endings.push(matches[1]);
}
}
}
// the array endings contains a list of all link extensions
Here's a working version of the code: http://jsfiddle.net/jfriend00/XHKaT/
The regular expression here matches a period followed by one or more non-period characters at the end of the string. The parenthesized grouping allows us to extra just the extension without the period which accomplishes the result you outlined.
This function performs as you need without reporting duplicates and maintaining the order in which the filename extensions are discovered.
function getLinkedFileExtensions() {
var i, len=document.links.length, ext=[], exts={};
for (i=0; i<len; i++) {
var a = document.links[i];
if (a.href && a.href.match(/\.([A-Za-z0-9]{1,4})$/)) {
var x = RegExp.$1;
if (!(x in exts)) {
exts[x] = true;
ext.push(x);
}
}
}
return ext;
}
var ext = [].map.call(document.links, function (a) {
return (a.href.match(this) || [])[1] || "";
}, /\.([a-zA-Z0-9]*)$/).filter(String);
http://jsfiddle.net/hZ9cU/
You can use jQuery to:
Get all of your anchor elements.
For each element you can access the .attr("href") value which will be your address string i.e. "myfile.mp3"
Then you can split the string on "." character and add the value at tokenArray[tokenArray.length-1] to your result list.
Or for vanilla JS try:
function getExtensions(){
var allAnchorTags = document.getElementsByTagName("a");
var extensions = new Array();
for(var i = 0; i < allAnchorTags.length; i++){
var tokenArray = allAnchorTags[i].href.split(".");
extensions[i] = tokenArray[tokenArray.length-1];
}
return extensions;
}
which does the same as described in my algorithm except with vanilla JS syntax. Give it a shot
See Feedle
var ext = a.href.split(".");
ext = ext[ext.length -1];
console.log(ext);
EDIT :
var d = document.getElementsByTagName("a"),
ext, i, j;
for(i = 0, j = d.length; i<j; i++){
ext = d[i].href.split(".");
ext = ext[ext.length -1];
console.log(ext);
}
I have a string like this:
string = "locations[0][street]=street&locations[0][street_no]=
34&locations[1][street]=AnotherStreet&locations[1][street_no]=43";
What must I do with this string so i can play with locations[][] as I wish?
You could write a parser:
var myStr = "locations[0][street]=street&locations[0][street_no]=34&locations[1][street]=AnotherStreet&locations[1][street_no]=43";
function parseArray(str) {
var arr = new Array();
var tmp = myStr.split('&');
var lastIdx;
for (var i = 0; i < tmp.length; i++) {
var parts = tmp[i].split('=');
var m = parts[0].match(/\[[\w]+\]/g);
var idx = m[0].substring(1, m[0].length - 1);
var key = m[1].substring(1, m[1].length - 1);
if (lastIdx != idx) {
lastIdx = idx;
arr.push({});
}
arr[idx * 1][key] = parts[1];
}
return arr;
}
var myArr = parseArray(myStr);
As Shadow wizard said, using split and eval seems to be the solution.
You need to initialize locations first, if you want to avoid an error.
stringArray=string.split("&");
for (var i=0;i<stringArray.length;i++){
eval(stringArray[i]);
}
However, you might need to pay attention to what street and street_no are.
As is, it will produce an error because street is not defined.
Edit: and you'll need to fully initialize locations with as many item as you'll have to avoid an error.