Regex to check if http or https exists in the string - javascript

So i have this code:
function validateText(str)
{
var tarea = str;
var tarea_regex = /^(http|https)/;
if(tarea_regex.test(String(tarea).toLowerCase()) == true)
{
$('#textVal').val('');
}
}
This works perfectly for this:
https://hello.com
http://hello.com
but not for:
this is a website http://hello.com asdasd asdasdas
tried doing some reading but i dont where to place * ? since they will check the expression anywhere on the string according here -> http://www.regular-expressions.info/reference.html
thank you

From the looks of it, you're just checking if http or https exists in the string. Regular expressions are a bit overkill for that purpose. Try this simple code using indexOf:
function validateText(str)
{
var tarea = str;
if (tarea.indexOf("http://") == 0 || tarea.indexOf("https://") == 0) {
// do something here
}
}

Try this:
function validateText(string) {
if(/(http(s?)):\/\//i.test(string)) {
// do something here
}
}

The ^ in the beginning matches the start of the string. Just remove it.
var tarea_regex = /^(http|https)/;
should be
var tarea_regex = /(http|https)/;

((http(s?))\://))
Plenty of ideas here : http://regexlib.com/Search.aspx?k=URL&AspxAutoDetectCookieSupport=1

Have you tried using a word break instead of the start-of-line character?
var tarea_regex = /\b(http|https)/;
It seems to do what I think you want. See here: http://jsfiddle.net/BejGd/

Related

How to apply DRY principle in javascript code snippet

I have this code snippet and it is obviously that it could be avoided repeating of those two regular expression in if condition because as you can see they differs only in one digit.
'phoneNumberRegexp': function (phoneCode, homeNumber) {
if (phoneCode === 372) {
return /[\s]*^\s*(\d[\s\-\u00b7]*){6,13}$/.test(homeNumber);
} else {
return /[\s]*^\s*(\d[\s\-\u00b7]*){8,13}$/.test(homeNumber);
}
}
Any idea how this could be done?
Thank you in advance
If you really want you can create a dynamic regex and use it
'phoneNumberRegexp': function (phoneCode, homeNumber) {
return new RegExp('[\\s]*^\\s*(\\d[\\s\\-\\u00b7]*){' + (phoneCode === 372 ? 6 : 8) + ',13}$').test(homeNumber);
}
Maybe using RegExp object.
'phoneNumberRegexp': function (phoneCode, homeNumber) {
var n = 8
if (phoneCode === 372) n = 6;
var pattern = "[\\s]*^\\s*(\\d[\\s\\-\\u00b7]*){"+n+",13}$";
var re = new RegExp(pattern);
return re.test(homeNumber);
}
You don't need to escape the individual regex's. Just use the .source method of each part to join individual regex fragments together. It's much easier to read and maintain.
'phoneNumberRegexp': (phoneCode, homeNumber) {
return new RegExp(/[\s]*^\s*(\d[\s\-\u00b7]*){/.source + (phoneCode===372?6:8) + /,13}$/.source).test(homeNumber);
}

How to check if a div contains a certain word and check if that certain word matchs a var?

So I am using Node.JS and doing a small multiplayer project.
Of course I'm using JavaScript for a lot of things.
I would like to check if a div contains a certain word and if that certain word matches a variable.
How would I do this with JavaScript?
I want something like:
var teststring = "hi";
if "<div id="test">" contents matches "teststring"
{
}
I also have jQuery so that's an option too!
I'm new to JavaScript so please fire away!
This was my attempt but it didn't work:
var socket = io.connect('http://*');
socket.on('field', function (data) {
if ($("#userid").text().indexOf(data) > -1)
{
window.alert('lol');
console.log(data);
$("#field").html(data);
}
else
{
window.alert("Something has gone wrong with the node server...");
}
});
Just check the contents of the div with the text() function of jQuery, like this:
var teststring = "hi";
if ($("#test").text().indexOf(teststring) > -1)
{
alert("Match!");
}
to get the value of the div you can use
var divValue = $('#test').text();
var teststring = "hi";
and to match with the variable;
if(divValue === teststring ){
alert('Two variables are matching !!');
}
and to search a String contains a substring you can use;
if (divValue.indexOf(teststring ) >= 0)
{
alert('Two variables are matching !!');
}
please visit http://jsfiddle.net/dennypanther/ojmyobL8/
In JavaScript u can do it lyk this :
var teststring = "hi";
var div=document.getElementById('test').innerHTML;
if(div.indexOf(testString) > -1 ){
// your code goes here
}

regex detect url and prepend http:// [duplicate]

This question already has answers here:
Adding http:// to all links without a protocol
(4 answers)
Closed 8 years ago.
I would like to detect url's that are entered in a text input. I have the following code which prepends http:// to the beginning of what has been entered:
var input = $(this);
var val = input.val();
if (val && !val.match(/^http([s]?):\/\/.*/)) {
input.val('http://' + val);
}
How would I go about adapting this to only append the http:// if it contains a string followed by a tld? At the moment if I enter a string for example:
Hello. This is a test
the http:// will get appended to hello, even though it's not a url. Any help would be greatly appreciated.
This simple function works for me. We don't care about the real existence of a TLD domain to gain speed, rather we check the syntax like example.com.
Sorry, I've forgotten that VBA trim() is not intrinsic function in js, so:
// Removes leading whitespaces
function LTrim(value)
{
var re = /\s*((\S+\s*)*)/;
return value.replace(re, "$1");
}
// Removes ending whitespaces
function RTrim(value)
{
var re = /((\s*\S+)*)\s*/;
return value.replace(re, "$1");
}
// Removes leading and ending whitespaces
function trim(value)
{
return LTrim(RTrim(value));
}
function hasDomainTld(strAddress)
{
var strUrlNow = trim(strAddress);
if(strUrlNow.match(/[,\s]/))
{
return false;
}
var i, regex = new RegExp();
regex.compile("[A-Za-z0-9\-_]+\\.[A-Za-z0-9\-_]+$");
i = regex.test(strUrlNow);
regex = null;
return i;
}
So your code, $(this) is window object, so I pass the objInput through an argument, using classical js instead of jQuery:
function checkIt(objInput)
{
var val = objInput.value;
if(val.match(/http:/i)) {
return false;
}
else if (hasDomainTld(val)) {
objInput.value = 'http://' + val;
}
}
Please test yourself: http://jsfiddle.net/SDUkZ/8/
The best solution i have found is to use the following regex:
/\.[a-zA-Z]{2,3}/
This detects the . after the url, and characters for the extension with a limit of 2/3 characters.
Does this seem ok for basic validation? Please let me know if you see any problems that could arise.
I know that it will detect email address's but this wont matter in this instance.
You need to narrow down your requirements first as URL detection with regular expressions can be very tricky. These are just a few situations where your parser can fail:
IDNs (госуслуги.рф)
Punycode cases (xn--blah)
New TLD being registered (.amazon)
SEO-friendly URLs (domain.com/Everything you need to know about RegEx.aspx)
We recently faced a similar problem and what we ended up doing was a simple check whether the URL starts with either http://, https://, or ftp:// and prepending with http:// if it doesn't start with any of the mentioned schemes. Here's the implementation in TypeScript:
public static EnsureAbsoluteUri(uri: string): string {
var ret = uri || '', m = null, i = -1;
var validSchemes = ko.utils.arrayMap(['http', 'https', 'ftp'], (i) => { return i + '://' });
if (ret && ret.length) {
m = ret.match(/[a-z]+:\/\//gi);
/* Checking against a list of valid schemes and prepending with "http://" if check fails. */
if (m == null || !m.length || (i = $.inArray(m[0].toLowerCase(), validSchemes)) < 0 ||
(i >= 0 && ret.toLowerCase().indexOf(validSchemes[i]) != 0)) {
ret = 'http://' + ret;
}
}
return ret;
}
As you can see, we're not trying to be smart here as we can't predict every possible URL form. Furthermore, this method is usually executed against field values we know are meant to be URLs so the change of misdetection is minimal.
Hope this helps.

How to add JavaScript if the URL has a certain word?

I want to add the the following jQuery to the following pages only.
http://www.mywebsite.com/check-8.asp
http://www.mywebsite.com/edit-8.asp
http://www.mywebsite.com/cart-8.asp
So this means I want to add it where URL string contains either check-8, cart-8 or edit-8.
What is the best way with jQuery or JavaScript?
var text = $('#system td.td-main').html();
if (text != null)
{
var newtext = text.replace("Pris","<div id=\"pricebox\">Pris").replace("mva\)","mva\)</div>");
$('#system td.td-main').html(newtext);
}
Thanks in advance.
if(location.pathname.indexOf('check-8') > 0 || location.pathname.indexOf('cart-8') > 0 || location.pathname.indexOf('edit-8') > 0){
//your code here
}
Or you can use the following:
function testForCheckEditCart() {
var patt = /(check|edit|cart)-8/i;
return patt.test(location.href);
}
If you want a pure JavaScript solution, use the window.location property:
if (window.location.href.match(/(check|cart|edit)-8/).length > 0) {
// do your stuff
}
You can use the string.match method to check if it matches a Regex. You can also factor it out if you need to know which one it is:
var matches = window.location.href.match(/(check|cart|edit)-8/);
if (matches.length > 0) {
var action = matches[1]; // will be check, cart or edit
}

How to detect whether a string is in URL format using javascript?

I think the question title seems to explain eveything.
I want to detect whether a string is in URL format or not using javascript.
Any help appreciated.
Try this-
function isUrl(s) {
var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/
return regexp.test(s);
}
usage: if (isUrl("http://www.page.com")) alert("is correct") else
alert("not correct");
function IsURL(url) {
var strRegex = "^((https|http|ftp|rtsp|mms)?://)"
+ "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+#)?" //ftp的user#
+ "(([0-9]{1,3}\.){3}[0-9]{1,3}" // IP形式的URL- 199.194.52.184
+ "|" // 允许IP和DOMAIN(域名)
+ "([0-9a-z_!~*'()-]+\.)*" // 域名- www.
+ "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\." // 二级域名
+ "[a-z]{2,6})" // first level domain- .com or .museum
+ "(:[0-9]{1,4})?" // 端口- :80
+ "((/?)|" // a slash isn't required if there is no file name
+ "(/[0-9a-z_!~*'().;?:#&=+$,%#-]+)+/?)$";
var re=new RegExp(strRegex);
return re.test(url);
}
Debuggex Demo (Improved version which matches also 'localhost')
try something like this:
function isUrl(s) {
var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)? (\/|\/([\w#!:.?+=&%#!\-\/]))?/
return regexp.test(s);
}
One for the future using the URL constructor and a basic try catch statement, it is supported in most modern browsers. Obviously no IE support...
const isUrl = (str) => {
try {
new URL(str);
return true;
} catch () {
return false;
}
}
If the URL is valid it will get parsed by the constructor and return true.
If the string is not a valid URL the constructor will chuck a syntax error that will get caught and return false.
Try this code. This expression is more complete and takes into account IP address:
function checkUrl(s) {
var regexp = /^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]#!\$&'\(\)\*\+,;=.]+$/
return regexp.test(s); }
You can use a regular expression for checking the string
^s?https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\#&=+\$,%#]+$
Regular Expressions and Javascript
Had the same task, but all of regex that I found online to check validity of a URL were failed in some test cases.
Here is the regex that worked everything:
/^(http:\/\/www\.|https:\/\/www\.|www\.)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?/
However, If the URL was like: google.com It accepted it as valid (which in my specific case, was considered as invalid)
It worked the best I had found. Worked like a charm!
When given the option, I prefer the simplest solution.
Use _.startsWith(string, 'http') if:
You don't mind if URL is invalid
You're sure the URL being checked will always start with 'http'
You don't expect the string to be another value that might start also with 'http'

Categories

Resources