This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 9 years ago.
RegExp gurus, heed my call!
This is probably super simple, but I've painted myself in a mental corner.
Taking a regular URL, split after the ?, which gives a string like variable=val&interesting=something¬interesting=somethingelse I want to extract the value of interesting.
The name of the variable I'm interested in can be a substring of another variable.
So the match should be
either beginning of string or "&" character
followed by "interesting="
followed by the string I want to capture
followed by either another "&" or end of string
I tried something along the lines of
[\^&]interesting=(.*)[&$]
but I got nothing...
Update
This is to be run in a Firefox addon on every get request, meaning that jQuery is not available and if possible I would like to avoid the extra string manipulation caused by writing a function.
To me this feels like a generic "extract part of a string with regex" but maybe I'm wrong (RegEx clearly isn't my strong side)
simple solution
var arr = "variable=val&interesting=something¬interesting=somethingelse".split("&");
for(i in arr) {
var splits = arr[i].split("=");
if(splits[0]=="interesting") alert(splits[1]);
}
also single line match
"variable=val&interesting=something¬interesting=somethingelse".match(/(?:[&]|^)interesting=((?:[^&]|$)+)/)[1]
function getValue(query)
{
var obj=location.search.slice(1),
array=obj.split('&'),
len=array.length;
for(var k=0;k<len;k++)
{
var elm=array[k].split('=');
if(elm[0]==query)return elm[1];
}
}
This function directly extract the query URL and return the corresponding value if present.
//usage
var get=getValue('interesting');
console.log(get);//something
If you're using the Add-on SDK for Firefox, you can use the url module:
https://addons.mozilla.org/en-US/developers/docs/sdk/latest/modules/sdk/url.html
This is much better than using regex.
Related
This question already has answers here:
Regular expression to get a string between two strings in Javascript
(13 answers)
Closed 2 years ago.
I have a string like this:
let temp = 'Hi {{username}}, Your request with request id: {{requestId}} has been processed. Please contact your nearest shop.'
I want this array from the string:
['userName', 'requestId']
I know I have to somehow use regular expressions to achieve this but I can't figure out the pattern for achieving this.
NOTE: This is just an example string and I want a more general approach to solve this problem coz the string may vary.
You need to use positive lookahead. Here is the regex which works for your case.
let temp = 'Hi {{username}}, Your request with request id: {{requestId}} has been processed. Please contact your nearest shop.'
temp.match(/(?<={{)(\w+)(?=}})/g)
This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 6 years ago.
I'm building a basic application which lets the user to share or continue their search status between sessions with # parameters in Javascript (I'm building this as a SPA so GET parameters won't always necessarily work).
In my app I could have a URI like: /items#rarity=rare,common,uncommon&cost=ascending&category=primary
If I wanted to check what state to set the cost filter in my react component, I'd want to extract asecnding and then check the ascending checkbox to set the state on page load.
If I use Javascript's split function combined with regex, I can capture all information on cost by doing:
var hash = window.location.hash;
hash = hash.split(/cost.*&/);
Right now, this will obviously return an array in two parts the first being /items#rarity=rare,common,uncommon& and category=primary as the split function will split on the condition supplied which in my case matches the string from regex.
Is there any way I can capture the extracted string from the split function so I can then parse the cost string?
No way. Oh, there is! Just wrap your regex in the capture group.
var s = '/items#rarity=rare,common,uncommon&cost=ascending&category=primary';
r = s.split(/(cost.*&)/);
console.log(r[0]);
console.log(r[1]); //there is the "thrown" part
console.log(r[2]);
To achieve expected result, use below
var x="/items#rarity=rare,common,uncommon&cost=ascending&category=primary";
console.log(x.split('cost=')[1].substring(0,x.split('cost=')[1].indexOf("&")));
http://codepen.io/nagasai/pen/RRyLmA
This question already has answers here:
Replace method doesn't work
(4 answers)
Closed 4 years ago.
I'm trying to further my understanding of regular expressions in JavaScript.
So I have a form that allows a user to provide any string of characters. I'd like to take that string and remove any character that isn't a number, parenthesis, +, -, *, /, or ^. I'm trying to write a negating regex to grab anything that isn't valid and remove it. So far the code concerning this issue looks like this:
var pattern = /[^-\+\(\)\*\/\^0-9]*/g;
function validate (form) {
var string = form.input.value;
string.replace(pattern, '');
alert(string);
};
This regex works as intended on http://www.infobyip.com/regularexpressioncalculator.php regex tester, but always alerts with the exact string I supply without making any changes in the calculator. Any advice or pointers would be greatly appreciated.
The replace method doesn't modify the string. It creates a new string with the result of the replacement and returns it. You need to assign the result of the replacement back to the variable:
string = string.replace(pattern, '');
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
add or update query string parameter
I am trying to replace the page number in the query string no matter what digit is to 1.
query string
index.php?list&page=2&sort=epub
javascript
window.location.href.replace(new RegExp("/page=.*?&/"), "page=1&")
Your code looks almost right; however:
you need to use either new RegExp or the special // regex syntax, but not both.
the replace method doesn't modify the string in-place, it merely returns a modified copy.
rather than .*?, I think it makes more sense to write \d+; more-precise regexes are generally less likely to go awry in cases you haven't thought of.
So, putting it together:
window.location.href = window.location.href.replace(/page=\d+/, "page=1");
This question already has answers here:
Replace method doesn't work
(4 answers)
Closed 4 years ago.
I have a simple string that I'm trying to manipulate:
Your order will be processed soon:
I grab the string using:
var html = jQuery('.checkout td h4').html();
I then try to replace the ':' using:
html.replace(":", ".");
When I print it out to the console, the string is the same as the original string. I've also tried making sure that the html variable is of type "string" by doing the following:
html = html + "";
That doesn't do anything. In searching around, it seems that the replace function does a RegEx search and that the ":" character might have a special meaning. I do not know how to fix this. Can someone help me get rid of this stinkin' colon?
Slightly related...
I couldn't get these answers to work to replace all ":" in a string for the url encoded character %3a and modified this answer by'xdazz' to work: Javascript: Replace colon and comma characters to get...
str = str.replace(/:\s*/g, "%3a");
In your case it would be
str = str.replace(/:\s*/g, ".");
If you wanted to replace all colons with periods on a longer string.
Hope this helps somebody else.
The replace function returns a new string with the replacements made.
Javascript strings are immutable—it cannot modify the original string.
You need to write html = html.replace(":", ".");
I think c++ is the only high level language where strings are mutable. This means that replace cannot modify the string it operates on and so must return a new string instead.
Try the following instead
var element = jQuery('.checkout td h4');
element.html(element.html().replace(":", "."));
Or, perhaps more correctly (since you may have multiple elements).
jQuery('.checkout td h4').html(
function (index, oldHtml) {
return oldHtml.replace(":", ".");
}
);