Html5 input types includes many new types.
(range , Email , date etc...)
For example :
<input type="url" >
I know that IE used to have regex store ( on one of its internal folders)
Question :
Can I see in what regexes does chrome use to validate the input ?
Is it under a viewable file or something ? / how can I see those regexs ?
I looked up the source code of Blink. Keep in mind I never saw it before today, so I might be completely off.
Assuming I found the right place -
For type="url" fields there is URLInputType, with the code:
bool URLInputType::typeMismatchFor(const String& value) const
{
return !value.isEmpty() && !KURL(KURL(), value).isValid();
}
typeMismatchFor is called from HTMLInputElement::isValidValue
bool HTMLInputElement::isValidValue(const String& value) const
{
if (!m_inputType->canSetStringValue()) {
ASSERT_NOT_REACHED();
return false;
}
return !m_inputType->typeMismatchFor(value) // <-- here
&& !m_inputType->stepMismatch(value)
&& !m_inputType->rangeUnderflow(value)
&& !m_inputType->rangeOverflow(value)
&& !tooLong(value, IgnoreDirtyFlag)
&& !m_inputType->patternMismatch(value)
&& !m_inputType->valueMissing(value);
}
KURL seems like a proper implementation of a URL, used everywhere in Blink.
In comparison, the implementation for EmailInputType, typeMismatchFor calls isValidEmailAddress, which does use a regex:
static const char emailPattern[] =
"[a-z0-9!#$%&'*+/=?^_`{|}~.-]+" // local part
"#"
"[a-z0-9-]+(\\.[a-z0-9-]+)*"; // domain part
static bool isValidEmailAddress(const String& address)
{
int addressLength = address.length();
if (!addressLength)
return false;
DEFINE_STATIC_LOCAL(const RegularExpression, regExp,
(emailPattern, TextCaseInsensitive));
int matchLength;
int matchOffset = regExp.match(address, 0, &matchLength);
return !matchOffset && matchLength == addressLength;
}
These elements and more can be found on the /html folder. It seems most of them are using proper parsing and checking of the input, not regular expressions.
Related
If I do:
var number = 3500;
alert(number.toLocaleString("hi-IN"));
I will get ३,५०० in Hindi.
But how can I convert it back to 3500.
I want something like:
var str='३,५००';
alert(str.toLocaleNumber("en-US"));
So, that it can give 3500.
Is it possible by javascript or jquery?
I think you are looking for something like:
https://github.com/jquery/globalize
Above link will take you to git project page. This is a js library contributed by Microsoft.
You should give it one try and try to use formt method of that plugin. If you want to study this plugin, here is the link for the same:
http://weblogs.asp.net/scottgu/jquery-globalization-plugin-from-microsoft
I hope this is what you are looking for and will resolve your problem soon. If it doesn't work, let me know.
Recently I've been struggling with the same problem of converting stringified number formatted in any locale back to the number.
I've got inspired by the solution implemented in NG Prime InputNumber component. They use Intl.NumberFormat.prototype.format() (which I recommend) to format the value to locale string, and then create set of RegExp expressions based on simple samples so they can cut off particular expressions from formatted string.
This solution can be simplified with using Intl.Numberformat.prototype.formatToParts(). This method returns information about grouping/decimal/currency and all the other separators used to format your value in particular locale, so you can easily clear them out of previously formatted string. It seems to be the easiest solution, that will cover all cases, but you must know in what locale the value has been previously formatted.
Why Ng Prime didn't go this way? I think its because Intl.Numberformat.prototype.formatToParts() does not support IE11, or perhaps there is something else I didn't notice.
A complete code example using this solution can be found here.
Unfortunately you will have to tackle the localisation manually. Inspired by this answer , I created a function that will manually replace the Hindi numbers:
function parseHindi(str) {
return Number(str.replace(/[०१२३४५६७८९]/g, function (d) {
return d.charCodeAt(0) - 2406;
}).replace(/[०१२३४५६७८९]/g, function (d) {
return d.charCodeAt(0) - 2415;
}));
}
alert(parseHindi("३५००"));
Fiddle here: http://jsfiddle.net/yyxgxav4/
You can try this out
function ConvertDigits(input, source, target) {
var systems = {
arabic: 48, english: 48, tamil: 3046, kannada: 3302, telugu: 3174, hindi: 2406,
malayalam: 3430, oriya: 2918, gurmukhi: 2662, nagari: 2534, gujarati: 2790,
},
output = [], offset = 0, zero = 0, nine = 0, char = 0;
source = source.toLowerCase();
target = target.toLowerCase();
if (!(source in systems && target in systems) || input == null || typeof input == "undefined" || typeof input == "object") {
return input;
}
input = input.toString();
offset = systems[target] - systems[source];
zero = systems[source];
nine = systems[source] + 9;
for (var i = 0 ; i < input.length; i++) {
var char = input.charCodeAt(i);
if (char >= zero && char <= nine) {
output.push(String.fromCharCode(char + offset));
} else {
output.push(input[i]);
}
}
return output.join("");
}
var res = ConvertDigits('१२३४५६७८९', 'hindi', 'english');
I got it from here
If you need a jquery thing then please try this link
Use the Globalize library.
Install it
npm install globalize cldr-data --save
then
var cldr = require("cldr-data");
var Globalize = require("globalize");
Globalize.load(cldr("supplemental/likelySubtags"));
Globalize.load(cldr("supplemental/numberingSystems"));
Globalize.load(cldr("supplemental/currencyData"));
//replace 'hi' with appropriate language tag
Globalize.load(cldr("main/hi/numbers"));
Globalize.load(cldr("main/hi/currencies"));
//You may replace the above locale-specific loads with the following line,
// which will load every type of CLDR language data for every available locale
// and may consume several hundred megs of memory!
//Use with caution.
//Globalize.load(cldr.all());
//Set the locale
//We use the extention u-nu-native to indicate that Devanagari and
// not Latin numerals should be used.
// '-u' means extension
// '-nu' means number
// '-native' means use native script
//Without -u-nu-native this example will not work
//See
// https://en.wikipedia.org/wiki/IETF_language_tag#Extension_U_.28Unicode_Locale.29
// for more details on the U language code extension
var hindiGlobalizer = Globalize('hi-IN-u-nu-native');
var parseHindiNumber = hindiGlobalizer.numberParser();
var formatHindiNumber = hindiGlobalizer.numberFormatter();
var formatRupeeCurrency = hindiGlobalizer.currencyFormatter("INR");
console.log(parseHindiNumber('३,५००')); //3500
console.log(formatHindiNumber(3500)); //३,५००
console.log(formatRupeeCurrency(3500)); //₹३,५००.००
https://github.com/codebling/globalize-example
A common scenario for this problem is to display a float number to the user and then want it back as a numerical value.
In that case, javascript has the number in the first place and looses it when formatting it for display. A simple workaround for the parsing is to store the real float value along with the formatted value:
var number = 3500;
div.innerHTML = number.toLocaleString("hi-IN");
div.dataset.value = number;
Then get it back by parsing the data attribute:
var number = parseFloat(div.dataset.value);
This is a Columbus's egg style answer. It works provided the problem is an egg.
var number = 3500;
var toLocaleString = number.toLocaleString("hi-IN")
var formatted = toLocaleString.replace(',','')
var converted = parseInt(formatted)
How can I test a URL if it is a relative or absolute path in Javascript or jQuery? I want to handle accordingly depending if the passed in URL is a local or external path.
if (urlString starts with http:// or https://)
//do this
FAST
If you only need to test for http:// or https:// then the most efficient way is:
if (urlString.indexOf('http://') === 0 || urlString.indexOf('https://') === 0)
UNIVERSAL
However, I would suggest a more universal, non case-sensitive, protocol-agnostic approach:
var r = new RegExp('^(?:[a-z+]+:)?//', 'i');
r.test('http://example.com'); // true - regular http absolute URL
r.test('HTTP://EXAMPLE.COM'); // true - HTTP upper-case absolute URL
r.test('https://www.exmaple.com'); // true - secure http absolute URL
r.test('ftp://example.com/file.txt'); // true - file transfer absolute URL
r.test('//cdn.example.com/lib.js'); // true - protocol-relative absolute URL
r.test('git+ssh://example.con/item'); // true - absolute URL with '+' in scheme
r.test('/myfolder/test.txt'); // false - relative URL
r.test('test'); // false - also relative URL
Explain the RegExp
^(?:[a-z+]+:)?//
^ - beginning of the string
(?: - beginning of a non-captured group
[a-z+]+ - any character of 'a' to 'z' or "+" 1 or more times
: - string (colon character)
)? - end of the non-captured group. Group appearing 0 or 1 times
// - string (two forward slash characters)
'i' - non case-sensitive flag
var pat = /^https?:\/\//i;
if (pat.test(urlString))
{
//do stuff
}
For protocol relative urls, use this regex:
/^https?:\/\/|^\/\//i
Depending on your needs, I think that a more reliable way to determine this is to use the built-in URL interface to construct a couple URL objects and compare origins.
new URL(document.baseURI).origin === new URL(urlToTest, document.baseURI).origin;
This allows the browser to parse and figure all this out for you, without having to worry about the side effects of edge cases.
Original Answer
A very fast and very flexible check is:
if (url.indexOf('://') > 0 || url.indexOf('//') === 0 ) {
// URL is absolute; either "http://example.com" or "//example.com"
} else {
// URL is relative
}
This will recognize an absolute URL, if:
URL contains "://" anywhere after the first character, or
URL starts with "//" (protocol relative)
No regex.
No jQuery or other dependency.
No hardcoded protocol names that make the condition case sensitive.
No string manipulation (e.g. toLowerCase or similar).
Only checks for "relative or absolute" but does not make any other sanity checks, can be used for web URLs or any internal protocol.
Update 1 (full function example)
Here is a quick function that returns true/false for the given URL:
function isUrlAbsolute(url) {
return (url.indexOf('://') > 0 || url.indexOf('//') === 0);
}
And same in ES6:
const isUrlAbsolute = (url) => (url.indexOf('://') > 0 || url.indexOf('//') === 0)
Update 2 (URLs inside URL param)
To additionally address URLs in format /redirect?target=http://example.org I recommend to use this code:
function isUrlAbsolute(url) {
if (url.indexOf('//') === 0) {return true;} // URL is protocol-relative (= absolute)
if (url.indexOf('://') === -1) {return false;} // URL has no protocol (= relative)
if (url.indexOf('.') === -1) {return false;} // URL does not contain a dot, i.e. no TLD (= relative, possibly REST)
if (url.indexOf('/') === -1) {return false;} // URL does not contain a single slash (= relative)
if (url.indexOf(':') > url.indexOf('/')) {return false;} // The first colon comes after the first slash (= relative)
if (url.indexOf('://') < url.indexOf('.')) {return true;} // Protocol is defined before first dot (= absolute)
return false; // Anything else must be relative
}
And the same in short form and ES 6
// Traditional JS, shortened
function isUrlAbsolute(url) {
return url.indexOf('//') === 0 ? true : url.indexOf('://') === -1 ? false : url.indexOf('.') === -1 ? false : url.indexOf('/') === -1 ? false : url.indexOf(':') > url.indexOf('/') ? false : url.indexOf('://') < url.indexOf('.') ? true : false;
}
// ES 6
const isUrlAbsolute = (url) => (url.indexOf('//') === 0 ? true : url.indexOf('://') === -1 ? false : url.indexOf('.') === -1 ? false : url.indexOf('/') === -1 ? false : url.indexOf(':') > url.indexOf('/') ? false : url.indexOf('://') < url.indexOf('.') ? true : false)
Here are some test cases:
// Test
console.log( isUrlAbsolute('http://stackoverflow.com') ) // -> true
console.log( isUrlAbsolute('//stackoverflow.com') ) // -> true
console.log( isUrlAbsolute('stackoverflow.com') ) // -> false
console.log( isUrlAbsolute('Ftp://example.net') ) // -> true
console.log( isUrlAbsolute('/redirect?target=http://example.org') ) // -> false
Update 3 (clarify relative URLs)
I've seen a few comments about invalid output:
Solution returns false for localhost
Answer fails on http:example.com
However, those URLs are indeed relative URLs. It's easy to test:
Create some folders on your localhost webroot, say a/b/c/
Create an index.html file and place following link into it: test
Open the index page in your browser: http://localhost/a/b/c/index.html and click on the link. You will end on http://localhost/a/b/c/localhost (and not on http://localhost)
Same happens when placing the link http:example.com into your index.html file. You end on http://localhost/a/b/c/example.com instead of http://example.com
Use a regex:
if (/^(?:[a-z]+:)?\/\//i.test(url))
Even more Universal RFC-compliant URI approach:
(?:^[a-z][a-z0-9+\.-]*:|\/\/) regex explanation
The other solutions listed here would fail for links like mailto:evan#nylas.com
RFC 3986 defines a Scheme as:
scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
3.1. Scheme
https://www.rfc-editor.org/rfc/rfc3986#section-3.1
While the protocol-relative url is technically valid as per section 4.2, Paul Irish has swung back the other way and considers this an anti-pattern. See http://www.paulirish.com/2010/the-protocol-relative-url/
4.2. Relative Reference
https://www.rfc-editor.org/rfc/rfc3986#section-4.2
If you'd like the regex without protocol-relative url's use:
^[a-z][a-z0-9+\.-]*:
To see a full list of other types of valid uri edge cases, check out the list here: https://en.wikipedia.org/wiki/URI_scheme
Nowdays, when a lot of services use protocol-relative URL (eg. //cdn.example.com/libary.js), this method is safer:
var isAbsolute = new RegExp('^([a-z]+://|//)', 'i');
if (isAbsolute.test(urlString)) {
// go crazy here
}
Don't use low-level stuff like regexp etc. These things have been solved by so many other people. Especially the edge cases.
Have a look at URI.js, it should do the job: http://medialize.github.io/URI.js/docs.html#is
var uri = new URI("http://example.org/");
uri.is("absolute") === true;
Here's a pretty robust solution for the browser environment:
Let the browser handle everything. No need for some complicated/error prone regexes.
const isAbsoluteUrl = (url) => {
const link = document.createElement('a');
link.href = url;
return link.origin + link.pathname + link.search + link.hash === url;
};
You can use a try, catch block to help with this. Rather than using a regular expression, you can use the URL interface at every step.
isExternalUrl (urlString) {
try {
const url = new URL(urlString) // THROW ON MISSING SCHEME
// DOES THIS URL ORIGINATE FROM THIS WEBSITE?
if (url.origin !== new URL(document.URL, document.baseURI).origin) {
return true // IS EXTERNAL URL
}
} catch (_e) {
// THROWS WHEN URL DOES NOT HAVE A SCHEME
new URL(urlString, document.baseURL) // THROW AN EXCEPTION IF THE URL IS TRULY MALFORMED IN SOME WAY
}
return false
}
var external = RegExp('^(https?:)?//');
if(external.test(el)){
// do something
}
EDIT:
With the next regular expression, you can even check if the link goes to the same domain or to an external one:
var external = RegExp('^((f|ht)tps?:)?//(?!' + location.host + ')');
if(external.test(el)){
// do something
}
var adress = 'http://roflmao.com';
if (adress.substr(0,7) == 'http://' || adress.substr(0,8) == 'https://') {
//
}
Neither of the mentioned solutions solved a redirect_url hack where the hacker entered /\/example.com or /\\/example.com. This is what I came up with to determine if our redirect url was relative:
var isRelative = !redirectUrl.match(/(\:|\/\\*\/)/); // Don't allow "//" (with optional "\"'s) or ":"
It should not start with a slash or hash, and it should not contain a double slash if not preceded by question mark or hash? I would not test that with a single regexp, it would be very complicated to match "no double slash".
function test(s) {
return s.charAt(0) != "#"
&& s.charAt(0) != "/"
&& ( s.indexOf("//") == -1
|| s.indexOf("//") > s.indexOf("#")
|| s.indexOf("//") > s.indexOf("?")
);
}
would be easier, clearer and imho faster.
Following function will get called when click event occurs on a hyperlink i.e 'a' tag if the tag contains url will be relative or contains same host then that new page will get loaded into same browser tab, If it contains different url then page will load in new browser tab
jQuery(document).ready(function() {
$('a').click(function(){
var a = this;
var a_href = $(this).attr('href');
var regex = new RegExp('^(?:[a-z]+:)?//', 'i');
if(a.host == location.host || regex.test(a_href) == false){
a.target = '_self';
}else{
a.target = '_blank';
}
});
});
var isExternalURL = url.toLowerCase().indexOf('http://') === 0 || url.toLowerCase().indexOf('https://') === 0 ;
How can I test a URL if it is a relative or absolute path in Javascript or jQuery? I want to handle accordingly depending if the passed in URL is a local or external path.
if (urlString starts with http:// or https://)
//do this
FAST
If you only need to test for http:// or https:// then the most efficient way is:
if (urlString.indexOf('http://') === 0 || urlString.indexOf('https://') === 0)
UNIVERSAL
However, I would suggest a more universal, non case-sensitive, protocol-agnostic approach:
var r = new RegExp('^(?:[a-z+]+:)?//', 'i');
r.test('http://example.com'); // true - regular http absolute URL
r.test('HTTP://EXAMPLE.COM'); // true - HTTP upper-case absolute URL
r.test('https://www.exmaple.com'); // true - secure http absolute URL
r.test('ftp://example.com/file.txt'); // true - file transfer absolute URL
r.test('//cdn.example.com/lib.js'); // true - protocol-relative absolute URL
r.test('git+ssh://example.con/item'); // true - absolute URL with '+' in scheme
r.test('/myfolder/test.txt'); // false - relative URL
r.test('test'); // false - also relative URL
Explain the RegExp
^(?:[a-z+]+:)?//
^ - beginning of the string
(?: - beginning of a non-captured group
[a-z+]+ - any character of 'a' to 'z' or "+" 1 or more times
: - string (colon character)
)? - end of the non-captured group. Group appearing 0 or 1 times
// - string (two forward slash characters)
'i' - non case-sensitive flag
var pat = /^https?:\/\//i;
if (pat.test(urlString))
{
//do stuff
}
For protocol relative urls, use this regex:
/^https?:\/\/|^\/\//i
Depending on your needs, I think that a more reliable way to determine this is to use the built-in URL interface to construct a couple URL objects and compare origins.
new URL(document.baseURI).origin === new URL(urlToTest, document.baseURI).origin;
This allows the browser to parse and figure all this out for you, without having to worry about the side effects of edge cases.
Original Answer
A very fast and very flexible check is:
if (url.indexOf('://') > 0 || url.indexOf('//') === 0 ) {
// URL is absolute; either "http://example.com" or "//example.com"
} else {
// URL is relative
}
This will recognize an absolute URL, if:
URL contains "://" anywhere after the first character, or
URL starts with "//" (protocol relative)
No regex.
No jQuery or other dependency.
No hardcoded protocol names that make the condition case sensitive.
No string manipulation (e.g. toLowerCase or similar).
Only checks for "relative or absolute" but does not make any other sanity checks, can be used for web URLs or any internal protocol.
Update 1 (full function example)
Here is a quick function that returns true/false for the given URL:
function isUrlAbsolute(url) {
return (url.indexOf('://') > 0 || url.indexOf('//') === 0);
}
And same in ES6:
const isUrlAbsolute = (url) => (url.indexOf('://') > 0 || url.indexOf('//') === 0)
Update 2 (URLs inside URL param)
To additionally address URLs in format /redirect?target=http://example.org I recommend to use this code:
function isUrlAbsolute(url) {
if (url.indexOf('//') === 0) {return true;} // URL is protocol-relative (= absolute)
if (url.indexOf('://') === -1) {return false;} // URL has no protocol (= relative)
if (url.indexOf('.') === -1) {return false;} // URL does not contain a dot, i.e. no TLD (= relative, possibly REST)
if (url.indexOf('/') === -1) {return false;} // URL does not contain a single slash (= relative)
if (url.indexOf(':') > url.indexOf('/')) {return false;} // The first colon comes after the first slash (= relative)
if (url.indexOf('://') < url.indexOf('.')) {return true;} // Protocol is defined before first dot (= absolute)
return false; // Anything else must be relative
}
And the same in short form and ES 6
// Traditional JS, shortened
function isUrlAbsolute(url) {
return url.indexOf('//') === 0 ? true : url.indexOf('://') === -1 ? false : url.indexOf('.') === -1 ? false : url.indexOf('/') === -1 ? false : url.indexOf(':') > url.indexOf('/') ? false : url.indexOf('://') < url.indexOf('.') ? true : false;
}
// ES 6
const isUrlAbsolute = (url) => (url.indexOf('//') === 0 ? true : url.indexOf('://') === -1 ? false : url.indexOf('.') === -1 ? false : url.indexOf('/') === -1 ? false : url.indexOf(':') > url.indexOf('/') ? false : url.indexOf('://') < url.indexOf('.') ? true : false)
Here are some test cases:
// Test
console.log( isUrlAbsolute('http://stackoverflow.com') ) // -> true
console.log( isUrlAbsolute('//stackoverflow.com') ) // -> true
console.log( isUrlAbsolute('stackoverflow.com') ) // -> false
console.log( isUrlAbsolute('Ftp://example.net') ) // -> true
console.log( isUrlAbsolute('/redirect?target=http://example.org') ) // -> false
Update 3 (clarify relative URLs)
I've seen a few comments about invalid output:
Solution returns false for localhost
Answer fails on http:example.com
However, those URLs are indeed relative URLs. It's easy to test:
Create some folders on your localhost webroot, say a/b/c/
Create an index.html file and place following link into it: test
Open the index page in your browser: http://localhost/a/b/c/index.html and click on the link. You will end on http://localhost/a/b/c/localhost (and not on http://localhost)
Same happens when placing the link http:example.com into your index.html file. You end on http://localhost/a/b/c/example.com instead of http://example.com
Use a regex:
if (/^(?:[a-z]+:)?\/\//i.test(url))
Even more Universal RFC-compliant URI approach:
(?:^[a-z][a-z0-9+\.-]*:|\/\/) regex explanation
The other solutions listed here would fail for links like mailto:evan#nylas.com
RFC 3986 defines a Scheme as:
scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
3.1. Scheme
https://www.rfc-editor.org/rfc/rfc3986#section-3.1
While the protocol-relative url is technically valid as per section 4.2, Paul Irish has swung back the other way and considers this an anti-pattern. See http://www.paulirish.com/2010/the-protocol-relative-url/
4.2. Relative Reference
https://www.rfc-editor.org/rfc/rfc3986#section-4.2
If you'd like the regex without protocol-relative url's use:
^[a-z][a-z0-9+\.-]*:
To see a full list of other types of valid uri edge cases, check out the list here: https://en.wikipedia.org/wiki/URI_scheme
Nowdays, when a lot of services use protocol-relative URL (eg. //cdn.example.com/libary.js), this method is safer:
var isAbsolute = new RegExp('^([a-z]+://|//)', 'i');
if (isAbsolute.test(urlString)) {
// go crazy here
}
Don't use low-level stuff like regexp etc. These things have been solved by so many other people. Especially the edge cases.
Have a look at URI.js, it should do the job: http://medialize.github.io/URI.js/docs.html#is
var uri = new URI("http://example.org/");
uri.is("absolute") === true;
Here's a pretty robust solution for the browser environment:
Let the browser handle everything. No need for some complicated/error prone regexes.
const isAbsoluteUrl = (url) => {
const link = document.createElement('a');
link.href = url;
return link.origin + link.pathname + link.search + link.hash === url;
};
You can use a try, catch block to help with this. Rather than using a regular expression, you can use the URL interface at every step.
isExternalUrl (urlString) {
try {
const url = new URL(urlString) // THROW ON MISSING SCHEME
// DOES THIS URL ORIGINATE FROM THIS WEBSITE?
if (url.origin !== new URL(document.URL, document.baseURI).origin) {
return true // IS EXTERNAL URL
}
} catch (_e) {
// THROWS WHEN URL DOES NOT HAVE A SCHEME
new URL(urlString, document.baseURL) // THROW AN EXCEPTION IF THE URL IS TRULY MALFORMED IN SOME WAY
}
return false
}
var external = RegExp('^(https?:)?//');
if(external.test(el)){
// do something
}
EDIT:
With the next regular expression, you can even check if the link goes to the same domain or to an external one:
var external = RegExp('^((f|ht)tps?:)?//(?!' + location.host + ')');
if(external.test(el)){
// do something
}
var adress = 'http://roflmao.com';
if (adress.substr(0,7) == 'http://' || adress.substr(0,8) == 'https://') {
//
}
Neither of the mentioned solutions solved a redirect_url hack where the hacker entered /\/example.com or /\\/example.com. This is what I came up with to determine if our redirect url was relative:
var isRelative = !redirectUrl.match(/(\:|\/\\*\/)/); // Don't allow "//" (with optional "\"'s) or ":"
It should not start with a slash or hash, and it should not contain a double slash if not preceded by question mark or hash? I would not test that with a single regexp, it would be very complicated to match "no double slash".
function test(s) {
return s.charAt(0) != "#"
&& s.charAt(0) != "/"
&& ( s.indexOf("//") == -1
|| s.indexOf("//") > s.indexOf("#")
|| s.indexOf("//") > s.indexOf("?")
);
}
would be easier, clearer and imho faster.
Following function will get called when click event occurs on a hyperlink i.e 'a' tag if the tag contains url will be relative or contains same host then that new page will get loaded into same browser tab, If it contains different url then page will load in new browser tab
jQuery(document).ready(function() {
$('a').click(function(){
var a = this;
var a_href = $(this).attr('href');
var regex = new RegExp('^(?:[a-z]+:)?//', 'i');
if(a.host == location.host || regex.test(a_href) == false){
a.target = '_self';
}else{
a.target = '_blank';
}
});
});
var isExternalURL = url.toLowerCase().indexOf('http://') === 0 || url.toLowerCase().indexOf('https://') === 0 ;
im trying to make a wep key generator and ive read how wep keys work but i really dont even know how to start making it. can anyone give me an example or direct me to a tutorial? i tried using google but no luck.
in javascript...
function generateHexString(length) {
// Use crypto.getRandomValues if available
if (
typeof crypto !== 'undefined'
&& typeof crypto.getRandomValues === 'function'
) {
var tmp = new Uint8Array(Math.max((~~length)/2));
crypto.getRandomValues(tmp);
return Array.from(tmp)
.map(n => ('0'+n.toString(16)).substr(-2))
.join('')
.substr(0,length);
}
// fallback to Math.getRandomValues
var ret = "";
while (ret.length < length) {
ret += Math.random().toString(16).substring(2);
}
return ret.substring(0,length);
}
// 40-/64-bit WEP: 10 digit key
alert("40-bit:" + generateHexString(10));
// 104-/128-bit WEP: 26 digit key
alert("104-bit:" + generateHexString(26))
// 256-bit WEP: 58 digit key
alert("256-bit:" + generateHexString(58));
If you wanted to generate something based on a fixed string input, there are methods for doing that as well... this should give you what you are looking for in terms of just a straight random hex string of the correct length.
I'm not sure if there is a standard passphrase to WEP generator, but most limit the input to printable characters, and the algorythms are generally weak.. best bet is to simply use WPA2PSK if you can.
I have the following code which detects which search engine and what search term has been used:
if (document.referrer.search(/google\.*/i) != -1) {
var start = document.referrer.search(/q=/);
var searchTerms = document.referrer.substring(start + 2);
var end = searchTerms.search(/&/);
end = (end == -1) ? searchTerms.length : end;
searchTerms = searchTerms.substring(0, end);
if (searchTerms.length != 0) {
searchTerms = searchTerms.replace(/\+/g, " ");
searchTerms = unescape(searchTerms);
alert('You have searched: '+searchTerms+' on google');
}
}
That actually works, but unfortunately it doesn't work as expected sometimes.
Sometimes if the referrer was even not google i get an alert with the search term as : ttp://www.domain.com ( without H at the start ) i think that may lead to the bug.
Appreciate any help!
Have you tried leveraging existing JS URL parsing schemes? It might save you a bunch of time. For example:
http://blog.stevenlevithan.com/archives/parseuri
It's cutting the "h" off because q= was not in the referrer string. So your start variable is -1. Then you add 2 to that to get your searchTerms var with a substring. You need to check for start to be equal to -1 and return.
I also think your "google" string detection is not bulletproof, I would rather do something like this...
var ref = document.referrer;
var pcol = ref.indexOf("://") + 3;
if(ref.indexOf("google.com") == pcol || ref.indexOf("www.google.com") == pcol) {
// It is google
}
One last thing, you should use decodeURIComponent instead of unescape.