Get portion of a string using Javascript - javascript

I have a string (from the pathname in the url) and I am trying to pull out part of it, but I'm having trouble.
This is what I have so far:
^(/svc_2/pub/(.*?).php)
The string is:
/svc_2/pub/stats/dashboard.php?ajax=1
How can I get a regex that returns /pub/stats/dashboard only?

If it's always that format (I'm assuming the /svc_2/ is always there) this should do it.
var s = "/svc_2/pub/stats/dashboard.php?ajax=1";
var match = s.match(/\/svc_2(.+)\./)[1];
But not if anything comes before that.

For this, using a regex is too much, but here is:
var string = "/svc_2/pub/stats/dashboard.php?ajax=1";
console.log(string.replace(/.*(\/pub.*)\.php.*$/,"$1"));
But you can do it, without a regex, like this
console.log(string.substr(6,string.indexOf(".php")-6));
In both cases, the console.log will give you /pub/stats/dashboard

This is not very flexible, but should work in this specific case.
var basedir = '/svc_2/', str = '/svc_2/pub/stats/dashboard.php?ajax=1';
str = str.substring(basedir.length, str.indexOf('.'));
alert(str);

Related

JS / Node.js string().replace() help also help editing URL

I am trying to edit a string in Node.js. I am developing a web proxy, and I need to rewrite some stuff.
What I need to rewrite is when there is two querystrings in a URL.
I just need the first one to stay but the rest to be modified to "&".
This is what I got.
.replace(new RegExp(/src="(.*?)?(.*?)?&_get=/gi),'src="$1' + '$2' + '&_get=')
But it's not replacing the querystring but the replace is working.
I also need this in string.replace() specifically. If this is not possible, I would like to know how I can get a URL to redirect to a link that replaces the querystring except the first one.
Based on your input output example in the comments, it seems like there's lots of ways you could do this.
One way would be to find the index of the last "?" and use the substring method to "replace" it.
let str = "balalala?query?_get=https://example.org"
let ind = str.lastIndexOf("?")
let newStr = str.substring(0,ind) + "&" + str.substring(ind+1)
If balalala? is always going to be constant, you can separate that out.
var source = 'balalala?'
var str = 'balalala?query?_get=https://example.org'
var rest = str.replace(source, '');
console.log(`${source}${rest.split('?').join('&')}`);

Parse string in javascript

How can I parse this string on a javascript,
var string = "http://www.facebook.com/photo.php?fbid=322916384419110&set=a.265956512115091.68575.100001022542275&type=1";
I just want to get the "265956512115091" on the string. I somehow parse this string but, still not enough to get what I wanted.
my code:
var newstring = string.match(/set=[^ ]+/)[0];
returns:
a.265956512115091.68575.100001022542275&type=1
try this :
var g=string.match(/set=[a-z]\.([^.]+)/);
g[1] will have the value
http://jsbin.com/anuhog/edit#source
You could use split() to modify your code like this:
var newstring = string.match(/set=[^ ]+/)[0].split(".")[1];
For a more generic approach to parsing query strings see:
Parse query string in JavaScript
Using the example illustrated there, you would do the following:
var newstring = getQueryVariable("set").split(".")[1];
You can use capturing group in the regex.
const str = 'http://www.facebook.com/photo.php?fbid=322916384419110&set=a.265956512115091.68575.100001022542275&type=1';
console.log(/&set=(.*)&/.exec(str)[1]);

Whats the best way to get an id from a URL written in different ways?

I'm trying to find a quick way to get an ID from a url like this in javascript or jquery?
https://plus.google.com/115025207826515678661/posts
https://plus.google.com/115025207826515678661/
https://plus.google.com/115025207826515678661
http://plus.google.com/115025207826515678661/posts
http://plus.google.com/115025207826515678661/
http://plus.google.com/115025207826515678661
plus.google.com/115025207826515678661/posts
plus.google.com/115025207826515678661/
plus.google.com/115025207826515678661
want to just get 115025207826515678661 from the URL
Is there a sure way to always get the ID regardless of the way its typed?
You could use this javascript which works on all the urls you posted:
var url, patt, matches, id;
url = 'https://plus.google.com/115025207826515678661/posts';
patt = /\/(\d+)(?:\/|$)/
matches = patt.exec(url);
id = matches[1];
Use the following regular expression to extract the value:
\/([0-9]+)\/?
Tested on all of your input strings and it worked on each.
The first and only group will have the number you're looking for
var pos=url.indexOf('com').
var str1=url.substr(pos+3,21);
if the 21 is not constant, then just check the indexOf('/') in the substr:
var pos=url.indexOf('com').
var str1=url.substr(pos+3);
pos=str1.indexOf('/');
var str2=str1.substr(0,pos);
alert(str2);
or, use some regexp magic as was written in a different answer here.
I believe you could create a new string, and then loop through the URL string, and copy any numbers into the new string, especially if the URLs never have other numerical characters.
Basically, stripping all but numerical characters.

Splitting string in javascript

How can I split the following string?
var str = "test":"abc","test1":"hello,hi","test2":"hello,hi,there";
If I use str.split(",") then I won't be able to get strings which contain commas.
Whats the best way to split the above string?
I assume it's actually:
var str = '"test":"abc","test1":"hello,hi","test2":"hello,hi,there"';
because otherwise it wouldn't even be valid JavaScript.
If I had a string like this I would parse it as an incomplete JSON which it seems to be:
var obj = JSON.parse('{'+str+'}');
and then use is as a plain object:
alert(obj.test1); // says: hello,hi
See DEMO
Update 1: Looking at other answers I wonder whether it's only me who sees it as invalid JavaScript?
Update 2: Also, is it only me who sees it as a JSON without curly braces?
Though not clear with your input. Here is what I can suggest.
str.split('","');
and then append the double quotes to each string
str.split('","'); Difficult to say given the formatting
if Zed is right though you can do this (assuming the opening and closing {)
str = eval(str);
var test = str.test; // Returns abc
var test1 = str.test1; // returns hello,hi
//etc
That's a general problem in all languages: if the items you need contain the delimiter, it gets complicated.
The simplest way would be to make sure the delimiter is unique. If you can't do that, you will probably have to iterate over the quoted Strings manually, something like this:
var arr = [];
var result = text.match(/"([^"]*"/g);
for (i in result) {
arr.push(i);
}
Iterate once over the string and replace commas(,) following a (") and followed by a (") with a (%) or something not likely to find in your little strings. Then split by (%) or whatever you chose.

Extracting a portion of the a href path using Javascript

I'm needing to extract a portion of an href attribute using javascript.
I've come up with a solution, but I'm not sure it's the best way. Below is my sample code. I've got a variable with the complete href path -- and all I'm interesting in extracting is the "Subcategory-Foobaz" portion.
I can assume it will always be sandwiched between the 2nd "/" and the "?".
I'm terrible with Regex, so I came up with what seems like a hokie solution using 2 "splits".
var path = "/Category-Foobar/Subcategory-Foobaz?cm_sp=a-bunch-of-junk-i-dont-care-about";
var subcat = path.split("/")[2].split("?")[0];
console.log(subcat);
Is this horrible? How would you do it?
Thanks
var path = "/Category-Foobar/Subcategory-Foobaz?cm_sp=a-bunch-of-junk-i-dont-care-about";
var subcat = path.split("/").pop().split("?")[0];
console.log(subcat);
Just a small change; use pop() to get the last element no matter how many /'s you have in your string
re = /\/[^\/]+\/([^?]+)/;
str = '/Category-Foobar/Subcategory-Foobaz?cm_sp=a-bunch-of-junk-i-dont-care-about';
matches = str.match(re);
console.log(matches);

Categories

Resources