how to get the parameter value from the url in javascript? [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can I get a specific parameter from location.search?
I have a url like the following.
http://localhost/xxx.php?tPath=&pid=37
I want to get the pid=37 but by its name because on time the url is like above and then when page refreshed then the url becomes like the following.
http://localhost/xxx.php?tPath=&action=xxx&pid=37&value=13&fname=aaaa&fone=4321122
So I want to get the pid=37. It might be a function to which I pass the pid as a parameter and it returns its value.
How will I do this?

Take a look at this or follow a solution like this:
function getParam( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
var frank_param = getParam( 'pid' );

Use the following function
function getParameterValue(name)
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null ) return "";
else return results[1];
}

Well, there are three answers already, which all use regex. But a regex is really the wrong tool for this job. As someone famously said, some people, when they have a problem, think, "I know, I'll use a regular expression!" Now they have two problems. Here are some of the reasons those answers are wrong:
If the "name" you're looking for has regex characters in it, you need to escape them, and all of the regexen fail if the URL uses an ampersand in the path part (not RFC-conformant, but some people might do it anyway).
They all fail if the parameter you're looking for has characters that are meaningful in a regex (for example, $).
Oh, and they all fail to account for multiple results (e.g., path?foo=bar&foo=baz), which is perfectly valid and relatively common in querystrings.
This really is a job for plain-ol' string functions, as given in this answer. I'd have written the function a little differently stylistically, but the algorithm is sound.

check this small utility http://jsfiddle.net/gwB2C/2/
usage :
var up = new URLParser();
var urlObj = up.parse('http://localhost/xxx.php?tPath=&action=xxx&pid=37&value=13&fname=aaaa&fone=4321122');
alert(urlObj.params['fname']); //alerts 'aaaa'
value of urlObj :
baseURL: "http://localhost/xxx.php"
params:{
action: "xxx"
fname: "aaaa"
fone: "4321122"
pid: "37"
tPath: ""
value: "13"
}
queryString: "tPath=&action=xxx&pid=37&value=13&fname=aaaa&fone=4321122"

Related

How to obtain index of subpattern in JavaScript regexp?

I wrote a regular expression in JavaScript for searching searchedUrl in a string:
var input = '1234 url( test ) 5678';
var searchedUrl = 'test';
var regexpStr = "url\\(\\s*"+searchedUrl+"\\s*\\)";
var regex = new RegExp(regexpStr , 'i');
var match = input.match(regex);
console.log(match); // return an array
Output:
["url( test )", index: 5, input: "1234 url( test ) 5678"]
Now I would like to obtain position of the searchedUrl (in the example above it is the position of test in 1234 url( test ) 5678.
How can I do that?
As far as I could tell it wasn't possible to get the offset of a sub-match automatically, you have to do the calculation yourself using either lastIndex of the RegExp, or the index property of the match object returned by exec(). Depending on which you use you'll either have to add or subtract the length of groups leading up to your sub-match. However, this does mean you have to group the first or last part of the Regular Expression, up to the pattern you wish to locate.
lastIndex only seems to come into play when using the /g/ global flag, and it will record the index after the entire match. So if you wish to use lastIndex you'll need to work backwards from the end of your pattern.
For more information on the exec() method, see here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec
The following succinctly shows the solution in operation:
var str = '---hello123';
var r = /([a-z]+)([0-9]+)/;
var m = r.exec( str );
alert( m.index + m[1].length ); // will give the position of 123
update
This would apply to your issue using the following:
var input = '1234 url( test ) 5678';
var searchedUrl = 'test';
var regexpStr = "(url\\(\\s*)("+searchedUrl+")\\s*\\)";
var regex = new RegExp(regexpStr , 'i');
var match = regex.exec(input);
Then to get the submatch offset you can use:
match.index + match[1].length
match[1] now contains url( (plus two spaces) due to the bracket grouping which allows us to tell the internal offset.
update 2
Obviously things are a little more complicated if you have patterns in the RegExp, that you wish to group, before the actual pattern you want to locate. This is just a simple act of adding together each group length.
var s = '~- [This may or may not be random|it depends on your perspective] -~';
var r = /(\[)([a-z ]+)(\|)([a-z ]+)(\])/i;
var m = r.exec( s );
To get the offset position of it depends on your perspective you would use:
m.index + m[1].length + m[2].length + m[3].length;
Obviously if you know the RegExp has portions that never change length, you can replace those with hard coded numeric values. However, it's probably best to keep the above .length checks, just in case you — or someone else — ever changes what your expression matches.
JS doesn't have a direct way to get the index of a subpattern/capturing group. But you can work around that with some tricks. For example:
var reStr = "(url\\(\\s*)" + searchedUrl + "\\s*\\)";
var re = new RegExp(reStr, 'i');
var m = re.exec(input);
if(m){
var index = m.index + m[1].length;
console.log("url found at " + index);
}
You can add the 'd' flag to the regex in order to generate indices for substring matches.
const input = '1234 url( test ) 5678';
const searchedUrl = 'test';
const regexpStr = "url\\(\\s*("+searchedUrl+")\\s*\\)";
const regex = new RegExp(regexpStr , 'id');
const match = regex.exec(input).indices[1]
console.log(match); // return [11, 15]
You don't need the index.
This is a case where providing just a bit more information would have gotten a much better answer. I can't fault you for it; we're encouraged to create simple test cases and cut out irrelevant detail.
But one important item was missing: what you plan to do with that index. In the meantime, we were all chasing the wrong problem. :-)
I had a feeling something was missing; that's why I asked you about it.
As you mentioned in the comment, you want to find the URL in the input string and highlight it in some way, perhaps by wrapping it in a <b></b> tag or the like:
'1234 url( <b>test</b> ) 5678'
(Let me know if you meant something else by "highlight".)
You can use character indexes to do that, however there is a much easier way using the regular expression itself.
Getting the index
But since you asked, if you did need the index, you could get it with code like this:
var input = '1234 url( test ) 5678';
var url = 'test';
var regexpStr = "^(.*url\\(\\s*)"+ url +"\\s*\\)";
var regex = new RegExp( regexpStr , 'i' );
var match = input.match( regex );
var start = match[1].length;
This is a bit simpler than the code in the other answers, but any of them would work equally well. This approach works by anchoring the regex to the beginning of the string with ^ and putting all the characters before the URL in a group with (). The length of that group string, match[1], is your index.
Slicing and dicing
Once you know the starting index of test in your string, you could use .slice() or other string methods to cut up the string and insert the tags, perhaps with code something like this:
// Wrap url in <b></b> tag by slicing and pasting strings
var output =
input.slice( 0, start ) +
'<b>' + url + '</b>' +
input.slice( start + url.length );
console.log( output );
That will certainly work, but it is really doing things the hard way.
Also, I left out some error handling code. What if there is no matching URL? match will be undefined and the match[1] will fail. But instead of worrying about that, let's see how we can do it without any character indexing at all.
The easy way
Let the regular expression do the work for you. Here's the whole thing:
var input = '1234 url( test ) 5678';
var url = 'test';
var regexpStr = "(url\\(\\s*)(" + url + ")(\\s*\\))";
var regex = new RegExp( regexpStr , 'i' );
var output = input.replace( regex, "$1<b>$2</b>$3" );
console.log( output );
This code has three groups in the regular expression, one to capture the URL itself, with groups before and after the URL to capture the other matching text so we don't lose it. Then a simple .replace() and you're done!
You don't have to worry about any string lengths or indexes this way. And the code works cleanly if the URL isn't found: it returns the input string unchanged.

Chrome Extension: Get Parameter from URL [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Get query string values in JavaScript
I am working on a extension for Chrome.
I already figured out how to get the URL from the actual Chrome-Tab.
chrome.tabs.getSelected(null, function(tab) {
document.getElementById('currentLink').innerHTML = tab.url;
});
But now i need to know how to get a specific Parameter from the URL.
I already tried out different Javascript-Functions but when i implement them, my Extension stops working.
So:
How can i get a specific parameter from the actual URL?
To get a query string in a single regexp, use:
var queryString = /^[^#?]*(\?[^#]+|)/.exec(tab.url)[1];
// Explanation of RegEx:
// ^[^#?]* (\?[^#]+ | )
// <Starts with any non-#/? string><query string OR nothing>
Then, use the following function to get the value of a specific key:
function getParameterByName(queryString, name) {
// Escape special RegExp characters
name = name.replace(/[[^$.|?*+(){}\\]/g, '\\$&');
// Create Regular expression
var regex = new RegExp("(?:[?&]|^)" + name + "=([^&#]*)");
// Attempt to get a match
var results = regex.exec(queryString);
return decodeURIComponent(results[1].replace(/\+/g, " ")) || '';
}
// Usage:
// Example: tab.url = "http://example.com/path?foo=bar&key_name=qs_value#"
var queryString = /\?[^#]+(?=#|$)|$/.exec(tab.url)[0];
var value = getParameterByName(queryString, 'qs_name');
// Result : value = "value";
// Example 2: Using the function to get a parameter from the current page's URL.
// (e.g inside content script)
var value = getParameterByName(location.search, 'qs_name');
// Result : value = "value"
Not exactly a regex, but this should work:
var queryString=url.match(/\?.+$)[0].split('#')[0]
This should work in most cases. I'll try to dig up the regex I had written for this some time ago.
Created simple function to get URL parameter in Javascript from a URL like this
.....58e/web/viewer.html?page=17&getinfo=33
function buildLinkb(param) {
var val = document.URL;
var url = val.substr(val.indexOf(param))
var n=parseInt(url.replace(param+"=",""));
alert(n+1);
}
buildLinkb("page");
OUTPUT : 18

PHP $_GET but with Javascript

I am able to get data from a URL with the following structure -
http://mydomain.com/test.php?word=hello
Using PHP I would use the following
$word = $_GET["word"];
Can anyone tell me if it is possible to achieve the same thing but using JavaScript?
Thanks
Yes, it is possible:
function gup( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
Source: Get URL Parameters Using Javascript
You can get these values using window.location.search. You can either roll your own code to parse this or use something like the answers to this question.

extracting a string out of another url or string

I want to extract the store/brand names out of the url or some title string.
so the url could be something like
"http://www.store1.com/brand1-Transform-Ultra-Prepaid-/"
and title could be " brand1 Transform Ultra Prepaid Phone "
I will keep the possible store names in an array like
var store_array = ['store1', 'brand1', 'brand2']
lets say if i search the above url or title, i should get the store1 and brand1 as a result.
how to do this in jquery, am beginner, please explain me in detail.
my initial idea is that i should below, but not sure. please help.
$.each( store_array, function(index, value) {
//what to do here
});
You can do:
var url = 'http://www.store1.com/brand1-Transform-Ultra-Prepaid-/',
path = url.split('/');
var store_array = path[path.length-2].split('-');
Demo: http://jsfiddle.net/jcGsp/
This all depends on how dynamic you want it to be, another options would be a regexp:
var url = 'http://www.store1.com/brand1-Transform-Ultra-Prepaid-/';
var store_array = url.replace(/http:\/\/www.store1.com\/([^\/]+)\//,'$1').split('-');
Demo: http://jsfiddle.net/fSpr3/
you can use the split function:
let's say the url is:
url=window.location.href;
url.split('http://www.store1.com/');
title=url[1];
if the word needed from "brand1-Transform-Ultra-Prepaid-" is "brand1" then split this again with:
title.split('-');
fixed_title=title[0];
I would define a function to do the matching, and run it on the strings I am interested in
function findMatches( str ){
return store_array.filter( function( el ){
return new RegExp( "\b"+el+"\b", "i" ).test( str );
});
}
var results1 = findMatches( 'http://www.store1.com/' );
var results2 = findMatches( " brand1 Transform Ultra Prepaid Phone " );
//etc
The \b ensures 'store1' etc are complete words (so, 'store1' wouldn't match 'megastore1') and the /i makes it case insensitive.
array.filter runs a function on every member of an array and returns a copy of the array with only those members for whose the function returns true. Note that array.filter is IE9 and above (you didn't specify the platform), for other browsers there is anice polyfill here https://gist.github.com/1031656
The findMatches function goes through all the strings in the list, turns them into regular expressions, and checks whether it is found in the string. If you have a lot of test string, it may be more efficient to run indexof
function findMatches( str ){
return store_array.filter( function( el ){
return ( "-1" !== str.indexOf( el ) );
});
}
Either will work. Note that this is not using jQuery, just plain JS (albeit ECMA5)

Getting Query Parameter from a URL which inturn has some URL with Query parameters

I've the following URL
http://somesite/somepage.aspx
I pass a query parameter value which has another URL with query parameters like this.
http://somesite/somepage.aspx?pageURL=http://someothersite/someotherpage.aspx?param1=value&source=http://anotheronesite/anotherpage
I need to get the pageURL value as the one in the bold letters. But i'm getting
http://someothersite/someotherpage.aspx?param1=value
and i'm not getting the source param. I'm using the following JavaScript function -
function getParameterByName( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
Any ideas?
You need to use URL encoding to encode the parameter. Otherwise & is treated as reserved character and belongs to the "base URL".
have u considered html url encoding the pageURL parameter?
this would greatly simplify your task

Categories