I need help with a regexp to get only the code parameter from this url:
URL: code=4%2FsAB_thYuaw3b12R0eLklKlc-qcvNg6f8E8pgvu_02MTTJE0NOcyvXkrTQrB3QK8209wSbIpLDEBrk8vUGYKQ41I&scope=https:.....
My Code:
getParameterByName(name) {
var url = window.location.href;
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$|)'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
this piece of code is returning `
4/sAB_thYuaw3b12R0eLklKlc-qcvNg6f8E8pgvu_02MTTJE0NOcyvXkrTQrB3QK8209wSbIpLDEBrk8vUGYKQ41I
In this case i need the first and only backslash to be a % sign instead..
I can't get it to work.
Thnx in advance!
It works for me!!!
function getUrlParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
Untested JavaScript regex:
var myRe = /=(.*)&/igm
var url = 'code=4%2FsAB_thYuaw3b12R0eLklKlc-qcvNg6f8E8pgvu_02MTTJE0NOcyvXkrTQrB3QK8209wSbIpLDEBrk8vUGYKQ41I&scope=https:';
var code = myRe.exec(url);
Use \bcode=([^&]+). It's sure to grab code query using word boundary 'code=' then capture any characters until it reaches & or the end.
test regex here: https://regex101.com/r/eSnB4S/1
Related
I have a simple script for replace prameter:
function replaceQueryParam(param, newval, search) {
//condition over accumulation & in url if I use null
if(newval == null){
ampersand = "";
} else{
ampersand = "&";
}
var regex = new RegExp("([?;&])" + param + "[^&;]*[;&]?");
var query = search.replace(regex, "$1").replace(/&$/, '');
return (query.length > 2 ? query + ampersand : "?") + (newval ? param + "=" + newval : '');
}
And I use it:
var str = window.location.search
str = replaceQueryParam('myParam', 'myValue', str)
window.location = window.location.pathname + str
It run perfect, but I want use the function edit to parameters with only one redirect. If I have it in onClick event, I cant use:
var str = window.location.search
str = replaceQueryParam('myParam', 'myValue', str)
window.location = window.location.pathname + str
var str = window.location.search
str = replaceQueryParam('SecondParam', 'null', str)
window.location = window.location.pathname + str
The second parameter I want null (I want delete second parameter from url) - if it by simple.
Thanks and sorry for my English
PS: It can by in jquery
All of my event:
$("#typ span").click(function() {
var url = window.location.href;
//if it exist
if (url.indexOf('typ') > -1){
var str = window.location.search
str = replaceQueryParam('typ', $(this).attr('id'), str)
window.location = window.location.pathname + str
//if its doesnt exist - add new
} else {
if (url.indexOf('?') > -1){
url += '&typ='+$(this).attr('id');
}else{
url += '?typ='+$(this).attr('id');
}
window.location.href = url;
}
});
if click on span I want do this (add or replace "typ") and null other parameter (if it exist) - with only one redirect.
Take a look at the existing URL interface.
Example:
const url = new URL('http://test.com/products?category=bears&page=3');
url.searchParams.set('category', 'puppies');
console.log(url.href); // Result: http://test.com/products?category=puppies&page=3
I'm new to JavaScript and I am trying to extract information from a query string on the web I created, if I load straight on the page without the query string the page will load but once I redirect from my form page to the page where I'm doing the parsing it freezes and crashes... can anyone help please! :(
http://main.xfiddle.com/7d679c3a/Project1/Commission.php
http://main.xfiddle.com/7d679c3a/Project1/contactForm.php
http://main.xfiddle.com/7d679c3a/Project1/DiceRoll.php
http://main.xfiddle.com/7d679c3a/Project1/IsEven.php
http://main.xfiddle.com/7d679c3a/Project1/palindrome.php
http://main.xfiddle.com/7d679c3a/Project1/part1.php
http://main.xfiddle.com/7d679c3a/Project1/passwordStrength.php
http://main.xfiddle.com/7d679c3a/Project1/allinOne.php
JavaScript Code
var $ = function(id)
{
return document.getElementById(id);
}
var formInfo = location.search();
formInfo = formInfo.substring(1, formInfo.length);
while (formInfo.indexOf("+") != -1)
{
formInfo = formInfo.replace("+", " ");
}
while (formInfo.indexOf("=") != -1)
{
formInfo.replace("=", " ");
}
formInfo = decodeURI(formInfo);
formInfo.replace("firstname", "");
formInfo.replace("lastname", "");
formInfo.replace("phonenumber", "");
formInfo.replace("postalcode", "");
formInfo.replace("startingmoney", "");
var infoArray = formInfo.split("&");
var firstName = infoArray[0];
var lastName = infoArray[1];
var phoneNumber = infoArray[2];
var postalCode = infoArray[3];
var startingMoney = infoArray[4];
$("playername").innerHTML = firstName + " " +lastName;
$("playerinfo").innerHTML = phoneNumber + " " + postalCode;
$("money").innerHTML = " $$" + startingMoney;
HTML Code
<div id="fireinfo">
<p id="playername"></p><br/>
<p id="playerinfo"></p>
<p id="money"></p>
</div>
I want to out put the information i get from the query string into the player name, player info and money id's.
Use this function to get query string value:
function getQueryString(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(window.location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
};
var firstname = getQueryString('firstname');
i need a javascript function to strip the user ID from a given URL.
for example. i have this URL http://www.example.com/member.php?id=100001877097904
how can i retrieve the ID of the user from that URL?
Thanks in advance.
function getParameterByName(url, name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(url);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
One possible solution:
var url = "http://www.example.com/member.php?id=100001877097904",
id = (url.match(/[?&#]id=(\d+)/) || []).pop();
console.log(id);
I am trying to get a Twitter oauth token using the below string. How can I "run" the string and then get the token?
This is the request string:
https://api.twitter.com/oauth/request_token?oauth_consumer_key=9TL0JGKTIv7GyOBeg8ynuxg&oauth_nonce=Xty48&oauth_signature=3skps99e6zkn0rcUGadVUEuHFon4%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1346603336
This is the result:
oauth_token=TBFdNoytaizrfMAWNZ6feqNz3BsozHk5AesIioX8u8Ec&oauth_token_secret=DtQ3jiUIeVdRcBAKwVQJRWpgKtEHi3m1ylk0nlsHCBj0&oauth_callback_confirmed=true
See answer to this question. It demonstrates how to get a value from the querystring.
Here, I've altered it to take the name value collection as a parameter:
function getParameterByName(name, qs)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(qs);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
Usage:
var result = "oauth_token=TBF...&oauth_token_secret=DtQ...";
var token = getParameterByName("oauth_token", result);
I want to check if a string is ending with ".php" extension, if not I want to add .html at the end. I have already tried various "slice" methods without success.
You can use Regex for that
var string1 = "www.example.com/index";
var newString = !/\.php$/i.test(string1)? string1+".html": string1;
// newString = "www.example.com/index.html"
Use (yourstring + '.html').replace(/\.php\.html$/, '.php') to do that:
var str1 = 'one.php';
var str2 = 'two';
var str3 = '.php.three.php';
var str4 = '.php.hey';
console.log((str1 + '.html').replace(/\.php\.html$/, '.php')); // Prints one.php
console.log((str2 + '.html').replace(/\.php\.html$/, '.php')); // Prints two.html
console.log((str3 + '.html').replace(/\.php\.html$/, '.php')); // Prints .php.three.php
console.log((str4 + '.html').replace(/\.php\.html$/, '.php')); // Prints .php.hey.html
Or perhaps:
function appendHTML(string) {
var html = string;
if (string.lastIndexOf('.php') === (string.length - 4)) {
html += '.html';
}
return html;
}
Well, slice() works ok for this task.
var s = "myfile.php";
if (s.slice(-4) != ".php")
s = s.slice(0, -4) + ".html";
Use regular expression to solve your problem.
/.php$/ is a regular expression that checks to see if a string ends with '.php'
For more information read: http://www.w3schools.com/js/js_obj_regexp.asp
Example Code:
str = "http://abc.com";
str = ( /\.php$/.test( str ) ) ? str : str + '.html'; // this is the line you want.
str === "http://abc.com.html" // returns true
Try something like this
function isPHP(str)
{
return str.substring(str.length - 4) == ".php";
}
Then you could do
str = isPHP(str) ? str : str + ".html";