Regex: ccTLD wildcard detection/removal in Javascript? - javascript

I have an url like this one:
http://xenodesystems.blogspot.com/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html
But the ".com" over there can change depending on the country, so that url also works with:
http://xenodesystems.blogspot.mx/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html
http://xenodesystems.blogspot.it/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html
http://xenodesystems.blogspot.fr/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html
etc.
What I need to do is replacing "xenodesystems.blogspot.*" with "blog.xenodesystems.com" and leave the rest of the URL intact, like this:
http://blog.xenodesystems.com/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html
Is this possible to do with javascript? I know blogger can redirect a domain, but I need to do it in pure Javascript explicitly. I know it's possible, it's just matter of finding the right regex, right?

Try this (JSFIDDLE). No regular expressions so it's much more efficient:
var str="http://xenodesystems.blogspot.mx/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html";
function xIndexOf(Val, Str, x)
{
if (x <= (Str.split(Val).length - 1)) {
Ot = Str.indexOf(Val);
if (x > 1) { for (var i = 1; i < x; i++) { var Ot = Str.indexOf(Val, Ot + 1) } }
return Ot;
}
}
var slash = (xIndexOf('/',str,3));
var dot = (xIndexOf('.',str,2));
str = str.substring(0,dot)+".com"+str.substring(slash)
alert(str)
xIndexOf function taken from here.

I think this is what you mean:
var urls = [
'http://xenodesystems.blogspot.mx/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html',
'http://xenodesystems.blogspot.it/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html',
'http://xenodesystems.blogspot.fr/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html',
'http://xenodesystems.blogspot.com.au/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html',
];
var ret = new Array;
var len = urls.length;
for (var i = 0; i < len; ++i) {
ret.push(urls[i].replace(/xenodesystems.blogspot(?:\.[a-zA-Z]+)+/,'xenodesystems.blogspot.com'));
}
console.log(ret);
OUTPUT
["http://xenodesystems.blogspot.com/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html",
"http://xenodesystems.blogspot.com/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html",
"http://xenodesystems.blogspot.com/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html",
"http://xenodesystems.blogspot.com/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html"]
Here's a fiddle

Related

Javascript - Dynamic variable

I am having problem to figure correct syntax to make those Javascript dynamic variable works:
I want to replace this code:
<code>
var res1 = res0.replace('[a1]', a1);
var res2 = res1.replace('[a2]', a2);
(...)
var res7 = res6.replace('[a7]', a7);
</code>
With something dynamic, like
<code>
for (var i = 1; i < 8; i++) {
**var str2 ="res" + i + " = res + i + .replace('[a + 'i']', window['a' + i])";**
eval(str2);
}
</code>
The ElementID is recovered from another Dynamic Variable, that works
<code>
for (var i = 1; i < 8; i++) {
var str ="a" + i + " = document.getElementById('a'+i).value";
eval(str);
}
</code>
General idea is simple.
Capture from a form, (input type text) and replace the strings called [a1], [a2], etc inside a textarea. Code works without dynamic variables.
Any idea is more than welcome.
Thank you
so don't use eval... bad practice, much bugs, little security, unexpected results...
it sounds like you just need an array.
(if you are using a for loop and eval - chances are you really want an array instead).
here is code that does not use eval()
reses = [] // of res0, res1 etc
for (let i = 1; i < 8; i++) {
reses[i].replace(`[a${i}]`, window[`a${i}`]);
}
for (let i = 1; i < 8; i++) {
let element =document.getElementById(`a${i}`).value;
}

get all variations of a string javascript

I want to get all the variations of a certain string. This string will be broken up by dashes. And the letters can only vary within those dashes.
For instance, let's say I pass DFI3-334-FG12 then I want to get all variations of that string for instance:
FI3-334-G12
FI3-334-F12
FI3-334-FG2
FI3-334-FG1
DI3-334-G12
DI3-334-F12
DI3-334-FG2
DI3-334-FG1
DF3-334-G12
DF3-334-F12
DF3-334-FG2
DF3-334-FG1
DFI-334-G12
DFI-334-F12
DFI-334-FG2
DFI-334-FG1
Can anyone assist with this? I have attempted loops but I only get as far as breaking it up and getting different parts of it:
FI3,DI3,DF3,DFI
334
G12,F12,FG2,FG1
This is my code:
$('#filter').on('click',function() {
var input = $('#code').val();
var parts = input.split("-");
var fixed = Array();
for(var i=0;i<parts.length; i++) {
if(parts[i].length != 3) {
k = 0;
fixed[i] = new Array();
for(var c=0;c<parts[i].length;c++) {
fixed[i][k] = parts[i].replace(parts[i].charAt(c),"");
k++;
}
} else {
fixed[i] = parts[i];
}
}
var final = Array();
$.each(fixed,function(i) {
$('#code_result').append(fixed[i] + "<br>");
})
});
If you know how many segments there are (3 in this case), you can use loops to get every possible combination.
See my example here:
http://jsfiddle.net/a6647m9e/1/
for(var i=0; i<parts[0].length; ++i) {
for(var j=0; j<parts[1].length; ++j) {
for(var k=0; k<parts[2].length; ++k) {
strings.push(parts[0][i]+'-'+parts[1][j]+'-'+parts[2][k]);
}
}
}
And just so you know, you're looking at (2^parts[0].length - 1) * (2^parts[1].length - 1) * (2^parts[2].length - 1) combinations (1575 in this case), taking out the blank combinations.
Note: this is all dependent on what your definition of "all possible combinations" is.
var string= 'DFI3-334-FG12';
var parts = string.split('-');
for(var i=0;i<parts[0].length;i++)
for(var j=0;j<parts[2].length;j++){
p1 = parts[0].substring(0,i)+parts[0].substring(i+1,parts[0].length);
p2 = parts[2].substring(0,j)+parts[2].substring(j+1,parts[2].length);
console.log(p1+'-'+parts[1]+'-'+p2);
}

Generate Array Javascript

I want to generate an array in jQuery/JS, which contains "code"+[0-9] or [a-z].
So it will look like that.
code0, code1 ..., codeA, codeB
The only working way now is to write them manually and I am sure this is a dumb way and there is a way to generate this automatically.
If you give an answer with a reference to some article where I can learn how to do similar stuff, I would be grateful.
Thank you.
For a-z using the ASCII table and the JavaScript fromCharCode() function:
var a = [];
for(var i=97; i<=122; i++)
{
a.push("code" + String.fromCharCode(i));
}
For 0-9:
var a = [];
for(var i=0; i<=9; i++)
{
a.push("code" + i);
}
I'm using the unicode hexcode to loop through the whole symbols from 0-z:
var arr = [];
for (var i = 0x30; i < 0x7b;i++){
// skip non word characters
// without regex, faster, but not as elegant:
// if(i==0x3a){i=0x41}
// if(i==0x5b){i=0x61}
char = String.fromCharCode(i);
while(!/\w/.test(char)){char = String.fromCharCode(i++)};
// generate your code
var res = "code"+char;
// use your result
arr.push(res);
}
console.log(arr);
Here goes your example.
Docs:
Unicode Table
for loop
fromCharCode
JS Array and it's methods
you can generate array in javascript by using following code.
var arr = [];
for (var i = 0; i < 5; i++) {
arr.push("code"+ i);
}
please refer following links.
https://developer.mozilla.org/en/docs/JavaScript/Reference/Global_Objects/Array
http://www.scriptingmaster.com/javascript/JavaScript-arrays.asp
a = [];
for(i = 48; i < 91; i++) {
if (i==58) i = 65
a.push("code" + String.fromCharCode(i));
}
alert(a.join(',')) // or cou can print to console of browser: console.log(a);

Extract domain name suffix from any url

I have a url in string format like this :
str="http://code.google.com"
and some other like str="http://sub.google.co.in"
i want to extract google.com from first one, and google.co.in from second string .
what i did is :
var a, d, i, ind, j, till, total;
a = document.createElement('a');
a.href = "http://www.wv.sdf.sdf.sd.ds..google.co.in";
d = "";
if (a.host.substr(0, 4) === "www.") {
d = a.host.replace("www.", "");
} else {
d = a.host;
}
till = d.indexOf(".com");
total = 0;
for (i in d) {
if (i === till) {
break;
}
if (d[i] === ".") {
total++;
}
}
j = 1;
while (j < total) {
ind = d.indexOf(".");
d = d.substr(ind + 1, d.length);
j++;
}
alert(d);
My code works but it works only for ".com" , it doesnt work for others like ".co.in","co.uk" till i specify them manually , Can anyone tell me the solution for this ? I dont mind even i need to change the full code, but it should work . Thanks
The only current practical solution (and even that doesn't work 100%) is to refer to the Public Suffix List in your code, and synchronise with that list as required.
There is no algorithm that can look at a domain name and figure out which part is the "registered domain name" and which parts are subdomains. It can't even be done by interrogating the DNS itself.
Regular expressions are quite powerful for such problems.
https://regex101.com/r/rW4rD8/1
The code below should fit this purpose.
var getSuffixOnly = function (url) {
var normalized = url.toLowerCase();
var noProtocol = normalized.replace(/.*?:\/\//g, "");
var splittedURL = noProtocol.split(/\/|\?+/g);
if (splittedURL.length > 1){
noProtocol = splittedURL[0].toString().replace(/[&\/\\#,+()$~%'":*?<>{}£€^ ]/g, '');
}
var regex = /([^.]{2,}|[^.]{2,3}\.[^.]{2})$/g;
var host = noProtocol.match(regex);
return host.toString();
};
getSuffixOnly(window.location.host);

Retrieve substring between two characters

I have string like this
var str = "#it
itA
itB
_
#et
etA
etB
_
etC
etD"
How can I retrieve elements between # and _. As of now I am splitting the text with new line but unable to workout this. Please help me on this. Please use this fiddle http://jsfiddle.net/h728C/2/
IF you simply want the FIRST string BETWEEN you can use:
var mys= str.substring(str.indexOf('#')+1,str.indexOf("_"));
this returns: "it itA itB"
I've posted some solution in fidde. It uses the Regex
var str = $('#a').text();
var pattern = /#([\s\S]*?)(?=_)/g;
var result = str.match(pattern);
for (var i = 0; i < result.length; i++) {
if (result[i].length > 1) {
result[i] = result[i].substring(1, result[i].length);
}
alert(result[i]);
}
Strip the end and beginning.
Edit
I've updated the fiddle and the code. Now it strips the beginning # and ending _.
You can use either. Whichever is convenient.
​
​
I don't really get why but this works:
var str = $('#a').text();
var results = [];
$.each(str.split("_"), function(){
var a = this.toString().split("#");
if(a.length===2) results.push(a[1]);
});
console.log(results);​
You can use this kind of regex:
str.replace(/\s/g, "").match(/#(.*?)_/g, "$1");
See this fiddle.
one line solution to get the array
var arrStr = str.split(/[#_]/);
I would not recommend using regex here as it can be done more efficiently through other methods.
function extractString(template, initChar, finalChar) {
let i = 0;
let data = [];
do {
if (template[i] == initChar) {
for (let j = i + 1; j < template.length; j++) {
if (template[j] == finalChar) {
data[data.length] = template.slice(i + 1, j);
i = j + 1;
break;
}
}
}
}
while (++i < template.length);
console.log(data)
return data;
}
extractString("#adj#, #brown# fox jumps over the lazy #dog#.","#","#");

Categories

Resources