Regex: find whatever comes after one thing before another thing - javascript

I want to find anything that comes after s= and before & or the end of the string. For example, if the string is
t=qwerty&s=hello&p=3
I want to get hello. And if the string is
t=qwerty&s=hello
I also want to get hello
Thank you!

\bs=([^&]+) and grabbing $1should be good enough, no?
edit: added word anchor! Otherwise it would also match for herpies, dongles...

Why don't you try something that was generically aimed at parsing query strings? That way, you can assume you won't run into the obvious next hurdle while reinventing the wheel.
jQuery has the query object for that (see JavaScript query string)
Or you can google a bit:
function getQuerystring(key, default_)
{
if (default_==null) default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}
looks useful; for example with
http://www.bloggingdeveloper.com?author=bloggingdeveloper
you want to get the "author" querystring's value:
var author_value = getQuerystring('author');

The simplest way to do this is with a selector s=([^&]*)&. The inside of the parentheses has [^&] to prevent it from grabbing hello&p=3 of there were another field after p.

You can also use the following expression, based on the solution provided here, which finds all characters between the two given strings:
(?<=s=)(.*)(?=&)
In your case you may need to slightly modify it to account for the "end of the string" option (there are several ways to do it, especially when you can use simple code manipulations such as manually adding a & character to the end of the string before running the regex).

Related

How to use `%value%` in javascript?

I am learning JavaScript and I see %value% in a code but I do not know what does it mean or how to use it. Can anyone please help me explain to me. Thank you very much.
var formattedLocation = HTMLworkLocation.replace("%data%", work.jobs[job].location);
"%data%" is just a literal string. This code will take the value of HTMLWorkLocation, look for the first occurrence of %data% in it, and replace that with the value of work.jobs[job].location, and store the resulting string in formattedLocation.
var work = {
jobs: [{
location: "Home office"
}]
};
var job = 0;
var HTMLworkLocation = "John is located at %data%";
var formattedLocation = HTMLworkLocation.replace("%data%", work.jobs[job].location);
console.log(formattedLocation);
This is probably part of a template system that's used to replace placeholders like %data% with values that come from a table.
You're using string.replace which takes a string or regular expression as it's first argument. Based on the code you posted it looks like you're looking for the string "%data%" (or whatever string you're looking for) in HTMLworkLocation and replacing it with the value in work.jobs[job].location. Then it is being stored in formattedLocation.
I would put a debugger; line after that line of code so you can see what the values are in the debugger console. That might help make more sense of things.
Here is more info on the str.replace method with some examples

Getting query string from re written URL

I have url "SampleProject/profile/aA12". How can I get the value of the id from my rewritten URL using javascript? I want to get the "aA12" value.
Im using htaccess rewrite to rewrite my URL. Im new in rewritting url's. Any help will be appreciated. More powers and thank you.
You can use regex.
Try
'SampleProject/profile/aA12'.match(/\SampleProject\/profile\/(\w+)/)
'SampleProject/profile/aA12/xxx'.match(/\SampleProject\/profile\/(\w+)/)
'aA12' will be matched in both cases.
There are going to be quite a few ways to achieve your goal with JavaScript. A simple solution could be something like this:
let myURL = "SampleProject/profile/aA12";
let result = myURL.split('/').pop();
// returns "aA12"
The .split('/') method is dividing your string up into an array using the / character, and .pop() is simply returning the last element of that array.
Hope this helps! If you were looking for more advanced matching, i.e. if you wanted to ignore a potential query string on the end of the URL parameter, you could use regular expressions.
Their is a many way that you can use to achieve the desired method i made you a code pen in this link
var url = "SampleProject/profile/aA12";
let res = url.split('/').pop();
console.log(res)
https://codepen.io/anon/pen/KQxNja

Underscore where: How to check for matching strings for case-insensitive

I'm using Underscore.js library to check for email address string inside my collection, if exists, like this:
var emailExists = this.model.get('emailmailCollection').where( {emailAddress:emailAddressValue});
It works perfectly for strings like aa#a.com, etc. but when I match emails like Aa#a.com & aa#a.com, it doesn't show it exists.
Is there a way to test for emails with case-insensitive in place.
You can use filter instead.
var emailExists = this.model.get('emailmailCollection').filter(function(email){
return email.get('emailAddress').toUpperCase() === emailAddressValue.toUpperCase();
});
Wherever you are getting Aa#a.com, use the .toLowerCase() method on it and on your input. This way, all of your data is all lowercase.
For example:
console.log("Hello WOrLD".toLowerCase())
returns
hello world
this is a really amateurish way and probably won't work for you, but that's what I would try.

Asymmetrical search for special characters in JavaScript

I'm trying to implement an asymmetrical search for a dictionary web app, so searching for ü, for example, will return only tokens that actually contain ü, but searching for u will return both u and ü. (This is so users who don't know how to type special characters can still search for them, but users who do know how to type them won't be inundated with the plain character forms unnecessarily.)
It has to all be client-side JavaScript without any external libraries.
I've managed to make the second search type work by running both the search term and the text I'm searching through the following function, effectively merging special characters with their plain counterparts:
function cleanUp(dirty) {
cleaned = dirty.replace(/[áàâãäāă]/ig,"a");
cleaned = cleaned.replace(/đ/ig,"d");
cleaned = cleaned.replace(/[éèêẽëēĕ]/ig,"e");
cleaned = cleaned.replace(/[íìîĩïīĭ]/ig,"i");
cleaned = cleaned.replace(/ñ/ig,"n");
cleaned = cleaned.replace(/[óòôõöōŏ]/ig,"o");
cleaned = cleaned.replace(/[úùûũüūŭ]/ig,"u");
return cleaned;
}
I then compare the strings to get my results with something like:
var search_term = cleanup(search_input.value);
var text_to_search = cleanup(main_text);
if (text_to_search.indexOf(search_term) > -1) ... //do something
It's not elegant, but it works. After cleaning up both strings the user can search for i.e. uber and get über even if they don't know how to type ü. But if they do know how, searching for über directly also returns things like uber, which is what I don't want.
I've already thought of things like checking for each special character separately for each search term or duplicating every dictionary entry that has a special character to produce a special-character and a plain-character version, but all of my ideas would seriously slow down the processing time for the search.
Any ideas are greatly appreciated.
The answer you posted sounds quite reasonable.
I would just like to suggest a cleaner way (pun intended) to code your cleanup() function and similar functions that do a series of string operations:
function cleanUp(dirty) {
return dirty
.replace(/[áàâãäāă]/ig,"a")
.replace(/đ/ig,"d")
.replace(/[éèêẽëēĕ]/ig,"e")
.replace(/[íìîĩïīĭ]/ig,"i")
.replace(/ñ/ig,"n")
.replace(/[óòôõöōŏ]/ig,"o")
.replace(/[úùûũüūŭ]/ig,"u");
}
I ended up checking to see if the search term contained any special characters, and if it did, I didn't run it through cleanup(), and compared it to the original dictionary entry instead of the cleaned one. Thanks for the comments everyone.

Use Regex in Javascript to get the filename in a URL

I'm using JavaScript to try and get the filename from the URL.
I can get it using this:
var fn=window.location.href.match(/([^/])+/g);
alert(fn[fn.length-1]); // get the last element of the array
but is there an easier way to get it (e.g., without having to use fn[fn.length-1]
Thanks!!
Add a $ at the end so you only get the last part:
window.location.href.match(/[^/]+$/g);
Personally, I try to use simple string manipulation for easy tasks like this. It makes for more readable code (for a person not very familiar with RegEx).
var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
Or simply:
var filename = window.location.pathname.substring(window.location.pathname.lastIndexOf('/')+1);
Additional Information
Not that it matters for something so trivial, but this method is also more performant than RegEx: http://jsperf.com/get-file-name
How about:
window.location.href.match(/\/([^/]+)$/)[1];
you can use .pop() to get the last element of an array;
alert(fn.pop());
There is a jQuery plugin that makes it easy to parse URLs and provide access to their different parts. One of the things it does is return the filename. Here's the plugin on GitHub:
https://github.com/allmarkedup/jQuery-URL-Parser
I would recommend using that and avoid reinventing the wheel. Regular expressions is an area of programming where this is particularly applicable.
I recommend to also remove any '#' or '?' string, so my answer is:
var fn = window.location.href.split('/').pop().replace(/[\#\?].*$/,'');
alert(fn);
split('/').pop() removes the path
replace(/[\#\?].*$/,'') replace '#' or '?' until the end $ by empty string

Categories