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
Related
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
Hi all I am framing a url with Query string in javascript as follows every thing works fine but a comm is coming in between the query string so can some one help me
<script type="text/javascript">
function RedirectLocation() {
var cntrl = "Q1;Q2";
var str_array = cntrl.split(';');
var cnt = str_array.length;
if (cnt == 0) {
location.href = '/callBack.aspx';
}
else {
var arr = [];
for (var i = 0; i < str_array.length; i++) {
str_array[i] = str_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
arr.push(str_array[i] + '=1');
if (i != str_array.length - 1) {
arr.push('&');
}
}
location.href = '/Sample.aspx?' + arr;
}
}
</script>
This is giving me the query string as follows Sample.aspx?Q1=1,&,Q2=1 I need this to be like `Sample.aspx?Q1=1&Q2=1
To remove the commas from a string you could simply do
s = s.replace(/,/g,'');
But in your specific case, what you want is not to add the commas. Change
location.href = '/Sample.aspx?' + arr;
to
location.href = '/Sample.aspx?' + arr.join('');
What happens is that adding an array to a string calls toString on that array and that function adds the commas :
""+["a","b"] gives "a,b"
Don't rely on the implicit string conversion (which concatenates the array elements with a comma as separator), explicitly .join the array elements with &:
var arr = [];
for (var i = 0; i < str_array.length; i++) {
str_array[i] = str_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
arr.push(str_array[i] + '=1');
}
location.href = '/Sample.aspx?' + arr.join('&');
Think about it like this: You have a set of name=value entries which you want to have separated by &.
You can use arr.join(glue) to concatenate Array elements with something inbetween. In your case glue would be an empty string arr.join("").
I have a URL like:
http://www.mysite.com/index.html?x=x1&x=x2&x=x3
How do I got the values like below, using JavaScript or JQuery:
var x='x1,x2,x3'
var url = "http://www.mysite.com/index.html?x=x1&x=x2&x=x3";
var params = url.match(/\?(.*)$/)[1].split('&');
var values = [];
for(var i=0; i<params.length; i++){
values.push( params[i].match(/=(.*)$/)[1] );
}
var result = values.join(","); // "x1,x2,x3"
EDIT: Here is a better solution that lets you select the parameter you want. This is something that I have found buried inside one of my projects, and I didn't write every part of it.
function $_GET(param) {
var query = window.location.search.substring(1);
var vars = query.split('&');
var values = [];
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (urldecode(pair[0]) == param) {
values.push(urldecode(pair[1]));
}
}
return values.join(",");
}
// Decode URL with the '+' character as a space
function urldecode(url) {
return decodeURIComponent(url.replace(/\+/g, ' '));
}
If you directly hit url you can use it as
var fieldValue = ['x1','x2','x3'];
var searchValue = 'x='+ fieldValue.join(',');
window.location.search = searchValue;
This will hit current url to search data for given parameters.
If you want to manually create url then hit search then
var url = "http://www.mysite.com/index.html";
window.location.href = url;
var fieldValue = ['x1','x2','x3'];
var searchValue = 'x='+ fieldValue.join(',');
window.location.search = searchValue;
Now you can search values, as per requirement.
I think what you need is PURL. Please refer https://github.com/allmarkedup/purl for detailed usage and guidelines
function GetUrlValue(VarSearch){
var SearchString = window.location.search.substring(1);
var VariableArray = SearchString.split('&');
for(var i = 0; i < VariableArray.length; i++){
var KeyValuePair = VariableArray[i].split('=');
if(KeyValuePair[0] == VarSearch){
return KeyValuePair[1];
}
}
}
read here http://javascriptproductivity.blogspot.in/2013/02/get-url-variables-with-javascript.html
You can easily find query string in jquery using jquery split
Try this function to get Query String as a array object:
function getUrlVars()
{
var vars = [];
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[1]);
}
return vars;
}
The function returns an array/object with your URL parameters and their values. So, you can use jquery .join() to convert it into comma separated values:
var result = vars.join(",");
Try in jsfiddle
Maybe use Regex:
var s = window.location.search;
var foo = s.match(/x=([0-9a-zA-Z]+)/g).join(",").replace(/x=/g, ""); // x1,x2,x3
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 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);
}