How to get IP value from textarea with regular expression - javascript

Here is a textarea.(IPv4, Domain)
96.17.109.65 fox.com
And I want to change IP value into another one.
like this,
74.125.71.106 fox.com
I guess it will be like
$('textarea').find('some regular expressions..').val('another one...');
Please help me. I just wanna learn regular expressions.. thanks.

Matching an IP address using regular expression is not as easy as it sounds. There are two methods available:
simple, but can lead to false-positives:
\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b
complex, but always correct:
\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b
If you want to replace it, you'll need something like this (using the simple RegExp as an example):
var textarea = $('textarea');
textarea.val(textarea.val().replace(/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g, '74.125.71.106'));

This uses a basic regex to find the seperator between ip and domain, it doesn't validate but it should do want you need:
var newIP = '74.125.71.106';
var $t = $('textarea');
$t.val($t.val().replace(/^([^\s]+)/mg, newIP + ' '));

Related

Extract characters in URL after certain character up to certain character

I'm trying to extract certain piece of a URL using regex (JavaScript) and having trouble excluding characters after a certain piece. Here's what I have so far:
URL: http://www.somesite.com/state-de
Using url.match(/\/[^\/]+$/)[0] I can extract the state-de like I want.
However when the URL becomes http://www.somesite.com/state-de?page=r and I do the same regex it pulls everything including the "?page=r" which I don't want. I want to only extract the state-de regardless of whats after it (looks like usually a "?" follows it)
This might work:
var arr = url.split("/")
arr[arr.length - 1].split("?")[0]
I'd recommend reading up on regular expressions in general. What you want to do here is make the regular expression stop when it hits the ? in the URL.
Using capturing groups to select which part of the match that you want might also be useful here.
Example:
url.match(/(\/[^\/?]+)(?:\?.*)?$/)[1]
I avoid overly complex RegExs when possible, so I tend to do this in multiple steps (with .replace()):
var stripped = url.replace(/[?#].*/, ''); // Strips anything after ? or #
You can now do the simpler transform to get the state, e.g.:
var state = stripped.split('/').pop()
If you want do it by regex try this one:
url.match(/https?:\/\/([a-z0-9-]+\.)+[a-z]+\/([a-z0-9_-])\/?(\?.*)?/)[1]
Or you could do it using JQuery:
var url = 'http://www.somesite.com/state-de?page=r#mark4';
// Create a special anchor element, set the URL to it
var a = $('<a>', { href:url } )[1];
console.log(a.hostname);
console.log(a.pathname);
console.log(a.search);
console.log(a.hash);

Regex expression to match the First url after a space followed

I want to match the First url followed by a space using regex expression while typing in the input box.
For example :
if I type www.google.com it should be matched only after a space followed by the url
ie www.google.com<SPACE>
Code
$(".site").keyup(function()
{
var site=$(this).val();
var exp = /^http(s?):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/;
var find = site.match(exp);
var url = find? find[0] : null;
if (url === null){
var exp = /[-\w]+(\.[a-z]{2,})+(\S+)?(\/|\/[\w#!:.?+=&%#!\-\/])?/g;
var find = site.match(exp);
url = find? 'http://'+find[0] : null;
}
});
Fiddle
Please help, Thanks in advance
you should be using a better regex to correctly match the query & fragment parts of your url. Have a look here (What is the best regular expression to check if a string is a valid URL?) for a correct IRI/URI structured Regex test.
But here's a rudimentary version:
var regex = /[-\w]+(\.[a-z]{2,})+(\/?)([^\s]+)/g;
var text = 'test google.com/?q=foo basdasd www.url.com/test?q=asdasd#cheese something else';
console.log(text.match(regex));
Expected Result:
["google.com/?q=foo", "www.url.com/test?q=asdasd#cheese"]
If you really want to check for URLs, make sure you include scheme, port, username & password checks just to be safe.
In the context of what you're trying to achieve, you should really put in some delay so that you don't impact browser performance. Regex tests can be expensive when you use complex rules especially so when running the same rule every time a new character is entered. Just think about what you're trying to achieve and whether or not there's a better solution to get there.
With a lookahead:
var exp = /[-\w]+(\.[a-z]{2,})+(\S+)?(\/|\/[\w#!:.?+=&%#!\-\/])?(?= )/g;
I only added this "(?= )" to your regex.
Fiddle

How to remove `//<![CDATA[` and end `//]]>` with javascript from string?

How to remove //<![CDATA[ and end //]]> with javascript from string?
var title = "<![CDATA[A Survey of Applications of Identity-Based Cryptography in Mobile Ad-Hoc Networks]]>" ;
needs to become
var title = "A Survey of Applications of Identity-Based Cryptography in Mobile Ad-Hoc Networks";
How to do that?
You can use the String.prototype.replace method, like:
title = title.replace("<![CDATA[", "").replace("]]>", "");
This will replace each target substring with nothing. Note that this will only replace the first occurrence of each, and would require a regular expression if you want to remove all matches.
Reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
You ought to be able to do this with a regex. Maybe something like this?:
var myString = "<![CDATA[A Survey of Applications of Identity-Based Cryptography in Mobile Ad-Hoc Networks]]>";
var myRegexp = /<!\[CDATA\[(.*)]]>/;
var match = myRegexp.exec(myString);
alert(match[1]);
I suggest this wider way to remove leading and trailing CDATA stuff :
title.trim().replace(/^(\/\/\s*)?<!\[CDATA\[|(\/\/\s*)?\]\]>$/g, '')
It will also work if CDATA header and footer are commented.
You must perform the OPPOSITE of what was originally done to the string to ENCODE it, which was this:-
mystr='<!CDATA[' + mystr.replaceAll(']]>',']]]]><![CDATA[>') + ']]>'
All the other answers on this page that suggest "replace" without using a loop are wrong.
The regular expresion /^(<!\[CDATA\[)|(]]>)$/gm worked for me without looping.

Whats the best way to get an id from a URL written in different ways?

I'm trying to find a quick way to get an ID from a url like this in javascript or jquery?
https://plus.google.com/115025207826515678661/posts
https://plus.google.com/115025207826515678661/
https://plus.google.com/115025207826515678661
http://plus.google.com/115025207826515678661/posts
http://plus.google.com/115025207826515678661/
http://plus.google.com/115025207826515678661
plus.google.com/115025207826515678661/posts
plus.google.com/115025207826515678661/
plus.google.com/115025207826515678661
want to just get 115025207826515678661 from the URL
Is there a sure way to always get the ID regardless of the way its typed?
You could use this javascript which works on all the urls you posted:
var url, patt, matches, id;
url = 'https://plus.google.com/115025207826515678661/posts';
patt = /\/(\d+)(?:\/|$)/
matches = patt.exec(url);
id = matches[1];
Use the following regular expression to extract the value:
\/([0-9]+)\/?
Tested on all of your input strings and it worked on each.
The first and only group will have the number you're looking for
var pos=url.indexOf('com').
var str1=url.substr(pos+3,21);
if the 21 is not constant, then just check the indexOf('/') in the substr:
var pos=url.indexOf('com').
var str1=url.substr(pos+3);
pos=str1.indexOf('/');
var str2=str1.substr(0,pos);
alert(str2);
or, use some regexp magic as was written in a different answer here.
I believe you could create a new string, and then loop through the URL string, and copy any numbers into the new string, especially if the URLs never have other numerical characters.
Basically, stripping all but numerical characters.

javascript jquery regexp replace

I'm trying to create a dynamic searchbar and i need help.
Right now im trying to replace a string with another string but i cant seem to succeed.
Im getting input from the user:
var location_keyword = $("#si_user_location").val();
Now i would like to replace a whitespace " " with a "|" to use this in my regexp as OR.
For example if the user wrote "Turkey Alanya", i want it to be "Turkey|Alanya" so that the search hits for both Turkey OR Alanya.
i tried something like this but it didnt work
var location_keyword = $("#si_user_location").val();
location_keyword.replace(" ","|");
var regexp_loc = new RegExp(location_keyword, "i");
i used to do this in PHP before with expressions such as:
preg_replace('/'.preg_quote($keyword).'/i', "<span>$0</span>", $string)
and i could replace strings caseinsensetive like this, how can i do this in js?
I used the last expression in PHP to highlight the keyword in the results, which i would like to do aswell in js.
hope i can get some help, thanks in advance! :)
best of regards,
alexander
There are two problems with the use of replace on this line:
location_keyword.replace(" ","|");
It does not modify the string - it returns a new string. You need to reassign the result of the call to the original variable otherwise you won't see the changed string.
It only replaces the first occurrence unless you use a regular expression with the g (global) flag.
Try this instead:
location_keyword = location_keyword.replace(/ /g, '|');
Try this:
location_keyword = location_keyword.replace(/\s+/,"|");
This should work fine:
location_keyword.replace(/ /g,"|");
Hope this helps! :)

Categories

Resources