Canvas not graphing exponents or multiple lines correctly - javascript

I have a program that graphs a line on an HTML canvas with JavaScript. The HTML contains a 500px by 500px canvas and a div with the id "LineBoxHolder" that has a certain number of items inside, which are from zero to infinity select elements of the class .equation, and for each one, depending on the selected value, a number of inputs of the type number and the class .eqNum. Here's a chart to clarify that part:
selected value | number of "number" inputs added
------------------------------------------------
number | 1
linear | 2
quadratic | 3
power | 2
exponential | 2
For example, if you have 3 select boxes, 1 with "linear" selected and 2 with "quadratic" selected, you get a total of 8 ".eqNum" inputs. Sorry if I'm not making much sense, I'ts midnight and I've had lots of homework lately (8th grade), but if this is too confusing I'll clean it up and add a bounty tomorrow. Anyways, here's the JavaScript code simplified down to what I think is the most important part. My problem, by the way, is that I can't graph multiple lines, and all types of lines except "number" and "linear" show up oddly.
function DrawCurrent()
{
//Set up environment
var cnvs = document.getElementById("cnvs");
cnvs.height = 500;
cnvs.width = 500;
var cont = cnvs.getContext("2d");
var imdt = cont.getImageData(0,0,500,500);
//Get the rest of the dimension and color values that need to be tested
var canvasXmin = document.getElementById("CanvasX-min").value;
var canvasYmin = document.getElementById("CanvasY-min").value;
var canvasXmax = document.getElementById("CanvasX-max").value;
var canvasYmax = document.getElementById("CanvasY-max").value;
var x_minList = document.querySelectorAll("#LineBoxHolder .x-min");
var y_minList = document.querySelectorAll("#LineBoxHolder .y-min");
var x_maxList = document.querySelectorAll("#LineBoxHolder .x-max");
var y_maxList = document.querySelectorAll("#LineBoxHolder .y-max");
var rgbaValue = document.querySelectorAll("#LineBoxHolder .lineColor");
var xyList = document.querySelectorAll("#LineBoxHolder .xOry");
var eqList = document.querySelectorAll("#LineBoxHolder .equation");
var numList = document.querySelectorAll("#LineBoxHolder .eqNum");
//Create variables to be used in graphing (Not all are nessecary, but they make for less repetitive and pointless coding)
var pseudoBase = 0;
var baseList = [];
var pseudoDependent = 0;
var pseudoDependentList = [];
var actualDependentList = [];
var dependentActual = 0;
var xMin = 0;
var xMax = 0;
var yMin = 0;
var yMax = 0;
var eqtn = "";
var numListNum = 0;
var a = 0;
var b = 0;
var c = 0;
var index = 0;
//Graph the lines
for (var z9 = 0 ; z9 < eqList.length/*Eqlist has 1 value for each line, so its length is equal to the number of lines*/ ; z9++ )
{
//Set values
xMin = x_minList[z9].value*1;
xMax = x_maxList[z9].value*1;
yMin = y_minList[z9].value*1;
yMax = y_maxList[z9].value*1;
eqtn = eqList[z9].value;
for ( var z10 = 0 ; z10 < 500 ; z10++ )
{
pseudoBase = canvasXmin*1 + (((Math.abs( canvasXmax - canvasXmin )) * z10)/500);
if ( pseudoBase >= xMin && pseudoBase <= xMax )
{
baseList.push( pseudoBase );
}
else
{
baseList.push( NaN );
};
}
if ( eqtn == "number" )
{
a = numList[numListNum].value;
numListNum++;
for ( var z12 = 0 ; z12 < 500 ; z12++)
{
pseudoDependent = a;
if ( pseudoDependent >= yMin && pseudoDependent <= yMax)
{
pseudoDependentList.push(pseudoDependent);
}
else
{
pseudoDependentList.push( NaN);
};
}
}
if ( eqtn == "linear" )
{
a = numList[numListNum].value;
numListNum++;
b = numList[numListNum].value;
numListNum++;
for ( var z12 = 0 ; z12 < 500 ; z12++)
{
pseudoDependent = (a*baseList[z12])*1 + b*1;
if ( pseudoDependent >= yMin && pseudoDependent <= yMax )
{
pseudoDependentList.push(pseudoDependent);
}
else
{
pseudoDependentList.push(NaN);
};
}
}
if ( eqtn == "quadratic" )
{
a = numList[numListNum].value;
numListNum++;
b = numList[numListNum].value;
numListNum++;
c = numList[numListNum].value;
numListNum++;
for ( var z12 = 0 ; z12 < 500 ; z12++)
{
pseudoDependent = (a* Math.pow(baseList[z12],2))+(b*1*baseList[z12])+c*1;
if ( pseudoDependent >= yMin && pseudoDependent <= yMax )
{
pseudoDependentList.push(pseudoDependent);
}
else
{
pseudoDependentList.push(NaN);
};
}
}
if ( eqtn == "power" )
{
a = numList[numListNum].value;
numListNum++;
b = numList[numListNum].value;
numListNum++;
for ( var z12 = 0 ; z12 < 500 ; z12++)
{
pseudoDependent = (a* Math.pow(baseList[z12],b));
if ( pseudoDependent >= yMin && pseudoDependent <= yMax )
{
pseudoDependentList.push(pseudoDependent);
}
else
{
pseudoDependentList.push(NaN);
};
}
}
if ( eqtn == "exponential" )
{
a = numList[numListNum].value;
numListNum++;
b = numList[numListNum].value;
numListNum++;
for ( var z12 = 0 ; z12 < 500 ; z12++)
{
pseudoDependent = (a* Math.pow(b,baseList[z12]));
if ( pseudoDependent >= yMin && pseudoDependent <= yMax )
{
pseudoDependentList.push(pseudoDependent);
}
else
{
pseudoDependentList.push(NaN);
};
}
}
for ( var z13 = 0 ; z13 < 500 ; z13++ )
{
dependentActual = 500-(((pseudoDependentList[z13]*1 + (0 - canvasYmin*1))*500)/Math.abs(canvasYmax-canvasYmin));
actualDependentList.push(dependentActual);
}
var storedindex = 0;
var currentIndex = 0;
for ( var z14 = 0 ; z14 < 500 ; z14++)
{
currentIndex = parseInt(Math.round((actualDependentList[z14]*2000) + (4*z14)));
console.log(currentIndex + " " + actualDependentList[z14] + " " + z14);
if (currentIndex >= 0 && currentIndex <= 999997 && pseudoDependentList[z14] != NaN && baseList[z14] != NaN)
{
environment.data[currentIndex] = newColorList[z9];
environment.data[currentIndex + 1] = newColorList[z9+1];
environment.data[currentIndex + 2] = newColorList[z9+2];
environment.data[currentIndex + 3] = 255;
}
if ( z14 > 0 && currentIndex < storedY && pseudoDependentList[z14] != NaN && baseList[z14] != NaN)
{
for ( var z20 = 1 ; z20 < Math.floor((storedY-currentIndex)/2000) ; z20++ )
{
index = currentIndex + (z20*2000);
if ( index < 999997 && index > 0 )
{
environment.data[index] = newColorList[z9];
environment.data[index + 1 ] = newColorList[z9+1];
environment.data[index + 2 ] = newColorList[z9+2];
environment.data[index + 3 ] = 255;
}
}
}
if ( z14 > 0 && currentIndex > storedY && pseudoDependentList[z14] != NaN && baseList[z14] != NaN )
{
for ( var z15 = 0 ; z15 < Math.floor((currentIndex-storedY)/2000) ; z15++ )
{
index = currentIndex + (z15*2000);
if ( index < 999997 && index > 0 )
{
environment.data[index] = newColorList[z9];
environment.data[index + 1 ] = newColorList[z9+1];
environment.data[index + 2 ] = newColorList[z9+2];
environment.data[index + 3 ] = 255;
}
}
}
storedY = currentIndex;
}
}
pixelDotter.putImageData( environment , 0 , 0 );
}
Also here's some sample HTML in case I was confusing:
<body onload = drawCurrent()>
<canvas id = "cnvs" height = "500px" width = "500px">
</canvas>
<div id = 'LineBoxHolder'>
<select class = "equation">
<option value = 'number'>A</option>
<option value = 'linear' selected = 'selected'>B</option>
<option value = 'quadratic'>C</option>
<option value = 'power'>D</option>
<option value = 'exponential'>E</option>
</select>
<!--Linear is selected so there are 2 number inputs-->
<input type = 'number' class = "eqNum">
<input type = 'number' class = "eqNum">
<select class = "equation">
<option value = 'number'>A</option>
<option value = 'linear' >B</option>
<option value = 'quadratic' selected = 'selected'>C</option>
<option value = 'power'>D</option>
<option value = 'exponential'>E</option>
</select>
<!-- Quadratic is selected so there are 23 number inputs-->
<input type = 'number' class = "eqNum">
<input type = 'number' class = "eqNum">
<input type = 'number' class = "eqNum">
</div>
Last quick note, JavaScript code assumes theres at least 1 line and that all the values it tries to get from html exist somewhere and are valid.

Related

Passing id value to a variable not working, only returning itstrue

I tried to add 2 field value and compare it with dropdown value with JS but its not working with variable.
$(document).ready(function() {
$('#SAVE,#CREATE').mouseover(function(e) {
var value89 = $('#P315_THRESHOLD').val() || 0;
var value20 = parseFloat($('#P315_C_RELEASE_REQUEST').val()) || 0;
var value21 = parseFloat($('#P315_O_RELEASE_REQUEST').val()) || 0;
var valuetot3 = value20 + value21 ;
var str = "";
if( value89 = '>250' && valuetot3 < 250 )
{
alert('CAPEX and OPEX request total value should be greater than 250 , current total is' +$('#P315_THRESHOLD').val() || 0);
}
});
});
Expected result is that it should throw alert for the conditions.
if( value89 = '>250' && valuetot3 < 250 )
........................^ this is an affectation instead of a comparaison
Either use value89 === '>250' or value89 >= 250
This should work according to your condition. Just remove = '>250' and replace >=250
<script>
$(document).ready(function() {
$('#SAVE,#CREATE').mouseover(function(e) {
var value89 = $('#P315_THRESHOLD').val() || 0;
var value20 = parseFloat($('#P315_C_RELEASE_REQUEST').val()) || 0;
var value21 = parseFloat($('#P315_O_RELEASE_REQUEST').val()) || 0;
var valuetot3 = value20 + value21 ;
var str = "";
if( value89 >=250 && valuetot3 < 250 ){
alert('CAPEX and OPEX request total value should be greater than 250 , current total is' +$('#P315_THRESHOLD').val() || 0);
}
});
});
</script>

Contribution margin percentage

I have made a formula to calculate contribution margin of a product, the thing is that the percentage is limited to 100%.
If we buy a product for 0.2€ and sell it for 99€, basically we earn more then 100% of the value.
$("#tb_calculator").change(function(){
$this = $(this);
var price_in = $this.find(".tb_price_in").val().replace(',', '.');
var price_out = $this.find(".tb_price_out").val().replace(',', '.');
var quantity = $this.find(".tb_quantity").val().replace(',', '.');
//var percentage = (price_out / price_in - 1)*100;
var percentage = (price_in / price_out);
var tb_value = (price_out*quantity - price_in*quantity);
//console.log(percentage);
var final_percentage = Math.round(((1-percentage)*100));
if (final_percentage === Infinity || final_percentage === "" || isNaN(final_percentage) || final_percentage < 0 || percentage < 0) {
var final_percentage = 0;
}
if (tb_value === Infinity || tb_value === "" || isNaN(tb_value)) {
var tb_value = 0;
}
function tofixed(val)
{
return parseFloat(val.toFixed(2));
}
$(".tb_count").val(tofixed(tb_value)+"kr - ("+final_percentage+"%)");
});
jsFiddle

Pause on MouseOver not working with Cross Browser Marquee II

I'm using Dynamic Drive's Cross Browser Marquee II scroller script find here. I had some help to alter the script where the content would have a random StartIndex on page load and the random part is working great; the forum thread for that is here. The problem I'm having now is that the altered script is not producing the pause on MouseOver function. I've made a JSFiddle here and tried everything I could think of to fix it but I'm stuck. The JavaScript is as follows:
function scrollmarquee() {
if (parseInt(cross_marquee.style.top) > (actualheight * (-1) + 8)) {
cross_marquee.style.top = parseInt(cross_marquee.style.top) - copyspeed + "px";
} else {
cross_marquee.style.top = parseInt(marqueeheight) + 8 + "px";
}
}
function marqueescroll(o) {
marqueePause(o.id);
o.srt += o.ss;
if ((o.ss < 0 && o.srt > o.h) || (o.ss > 0 && o.srt < o.ph)) {
o.s.style.top = o.srt + 'px';
} else {
o.srt = o.ss < 0 ? o.ph : o.h;
o.s.style.top = o.srt + 'px';
}
o.to = setTimeout(function () {
marqueescroll(o);
}, 60);
}
function marquee(o) {
var id = o.ID,
ss = o.Speed,
i = o.StartIndex,
srt = o.AutoDelay,
p = document.getElementById(id),
s = p ? p.getElementsByTagName('DIV')[0] : null,
ary = [],
z0 = 0;
if (s) {
var clds = s.childNodes,
o = marquee[id] = {
id: id,
p: p,
h: -s.offsetHeight,
ph: p.offsetHeight,
s: s,
ss: typeof (ss) == 'number' && ss != 0 ? ss : -2,
srt: 0
}
for (; z0 < clds.length; z0++) {
if (clds[z0].nodeType == 1) {
ary.push(clds[z0]);
}
}
ary[i] ? o.srt = -ary[i].offsetTop : null;
o.s.style.position = 'absolute';
o.s.style.top = o.srt + 'px';
typeof (srt) == 'number' && srt > 1 ? marqueeAuto(id, srt) : null;
}
}
function marqueeAuto(id, ms) {
var o = marquee[id];
o ? o.to = setTimeout(function () {
marqueescroll(o);
}, ms || 200) : null;
}
function marqueePause(id) {
var o = marquee[id];
o ? clearTimeout(o.to) : null;
}
function marqueeInit() {
marquee({
ID: 'marqueecontainer', // the unique ID name of the parent DIV.(string)
AutoDelay: 2000, //(optional) the delay before starting scroll in milli seconds. (number, default = no auto scroll)
Speed: -1, //(optional) the scroll speed, < 0 = up. > 0 = down. (number, default = -2)
StartIndex: Math.floor(Math.random() * 4) //(optional) the index number of the element to start. (number, default = 0)
});
}
if (window.addEventListener) window.addEventListener("load", marqueeInit, false);
else if (window.attachEvent) window.attachEvent("onload", marqueeInit);
else if (document.getElementById);
window.onload = marqueeInit;
It's probably a real simple fix I'm just not catching. Any help would greatly be appreciated. Also, does anyone know of a way to make the scroller where there will be no blank space between the last and first items being scrolled in the list?
This has now been fixed and is completely cross browser and twitter bootstrap friendly. You can check out the new edited jsfiddle here. Fixed javascript is as follows:
function marqueescroll(o) {
marqueePause(o.id);
o.srt += o.ss;
if ((o.ss < 0 && o.srt > o.sz) || (o.ss > 0 && o.srt < (o.w ? -o.sz : o.psz))) {
o.s.style[o.m] = o.srt + 'px';
} else {
o.srt = (o.w ? 0 : o.ss < 0 ? o.psz : o.sz) + o.ss;
o.s.style[o.m] = o.srt + 'px';
}
o.to = setTimeout(function () {
marqueescroll(o);
}, 30);
}
function marquee(o) {
var id = o.ID,
m = o.Mode,
ss = o.Speed,
i = o.StartIndex,
srt = o.AutoDelay,
p = document.getElementById(id),
s = p ? p.getElementsByTagName('DIV')[0] : null,
clds = s ? s.childNodes : [],
ary = [],
sz, l, z0 = 0;
if (s && !marquee[id]) {
var m = typeof (m) == 'string' && m.charAt(0).toUpperCase() == 'H' ? ['left', 'offsetLeft', 'offsetWidth'] : ['top', 'offsetTop', 'offsetHeight'],
sz = p[m[2]],
slide = document.createElement('DIV'),
c;
slide.style.width = 'inherit',//added this for fluid bootstrap width
slide.style.position = s.style.position = 'absolute';
for (; z0 < clds.length; z0++) {
if (clds[z0].nodeType == 1) {
if (m[0] == 'left') {
clds[z0].style.position = 'absolute';
clds[z0].style.left = sz * ary.length + 'px';
clds[z0].style.top = '0px';
}
ary.push([clds[z0], clds[z0][m[1]]]);
}
}
l = ary[ary.length - 1][0];
o = marquee[id] = {
m: m[0],
id: id,
p: p,
sz: -(l[m[1]] + l[m[2]]),
psz: sz,
s: slide,
ss: typeof (ss) == 'number' && ss != 0 ? ss : -2,
w: o.Wrap !== false
}
o.s.appendChild(s);
c = s.cloneNode(true);
c.style.left = c.style.top = '0px';
c.style[m[0]] = o.sz * (ss > 0 ? 1 : -1) + 'px';
o.w ? o.s.appendChild(c) : null;
o.srt = ary[i] ? -ary[i][1] : 0;
o.s.style.position = 'absolute';
o.s.style[m[0]] = o.srt + 'px';
p.appendChild(o.s);
p.style.overflow = 'hidden';
typeof (srt) == 'number' && srt > 1 ? marqueeAuto(id, srt) : null;
}
}
function marqueeAuto(id, ms) {
var o = marquee[id];
o ? o.to = setTimeout(function () {
marqueescroll(o);
}, ms || 200) : null;
}
function marqueePause(id) {
var o = marquee[id];
o ? clearTimeout(o.to) : null;
}
function marqueeInit() {
marquee({
ID: 'marqueecontainer', // the unique ID name of the parent DIV. (string)
Mode: 'vertical', // the display type, 'vertical' or 'horizontal' (string. defalut = 'vertical')
AutoDelay: 2000, //(optional) the delay before starting scroll in milli seconds. (number, default = no auto scroll)
Speed: -2, //(optional) the scroll speed, < 0 = up. > 0 = down. (number, default = -2)
Wrap: true, //(optional) true = no gap, false = gap. (boolean, default = true)
StartIndex: Math.floor(Math.random() * 4) //(optional) the index number of the element to start. (number, default = 0)
});
}
if (window.addEventListener) window.addEventListener("load", marqueeInit, false);
else if (window.attachEvent) window.attachEvent("onload", marqueeInit);
else if (document.getElementById) window.onload = marqueeInit;

Cannot call method 'toString' of undefined | There is something wrong with my code?

Apparently my script is right, could someone help me with this? When I see the console it shows the message Cannot call method 'toString' of undefined.
Could it be a problem with the ID selector? Can I use just one function instead of using one for validation and another to run my function?
/* ==== CPF Validator ==== */
function validar_cpf(cpf)
{
regex = /\./g;
cpf = cpf.toString().replace(regex,'');
cpf_split = cpf.split('-');
numero = cpf_split[0];
dv = cpf_split[1];
numero_init = numero.toString() + dv.toString();
if(numero_init.length < 11)
return false
var somatorio = 0;
for(i = 10, n = 0; i >= 2 ; i--, n++){
m = numero.charAt(n) * i;
somatorio += m;
}
dv1 = somatorio / 11;
dv1 = parseInt(dv1);
resto = somatorio % 11;
if(resto < 2)
dv1 = 0;
else
dv1 = Math.abs(11 - resto);
numero += dv1.toString();
somatorio = 0;
for(i = 11, n= 0; i >= 2 ; i--, n++ ){
m = numero.charAt(n) * i;
somatorio += m;
}
resto = somatorio % 11;
if(resto < 2)
dv2 = 0;
else
dv2 = 11 - resto;
numero += dv2.toString();
if(numero == numero_init)
return true;
else
return false;
}
function ValidaCpf()
{
if (validar_cpf(cpf))
{
document.getElementById('first-cpf').classList.add('hide');
document.getElementById('second-cpf').classList.remove('hide');
document.getElementById('cpf').classList.add('form_invalido');
document.getElementById('cpf').classList.remove('form_valido');
}
else {
document.getElementById('first-cpf').classList.remove('hide');
document.getElementById('second-cpf').classList.add('hide');
document.getElementById('cpf').classList.remove('form_invalido');
document.getElementById('cpf').classList.add('form_valido');
}
}
I found a solution
/* ==== CPF Validator ==== */
function ValidaCpf(input) {
var value = input.value,
result = true,
invalids = new Array(
'111.111.111-11',
'222.222.222-22',
'333.333.333-33',
'444.444.444-44',
'555.555.555-55',
'666.666.666-66',
'777.777.777-77',
'888.888.888-88',
'999.999.999-99',
'000.000.000-00',
'11111111111',
'22222222222',
'33333333333',
'44444444444',
'55555555555',
'66666666666',
'77777777777',
'88888888888',
'99999999999',
'00000000000'
);
for( var i = 0; i<invalids.length; i++) {
if( invalids[i] == value) {
result = false;
}
}
add = 0;
value = value.replace("-","");
value = value.replace(/\./g,"");
for( var j=0; j < 9; j++ ) {
add += parseInt(value.charAt(j),10) * (10-j);
}
rev = 11 - ( add % 11 );
if( rev == 10 || rev == 11) {
rev = 0;
}
if( rev != parseInt(value.charAt(9),10) ) {
result = false;
}
add = 0;
for( var k=0; k < 10; k++ ) {
add += parseInt(value.charAt(k),10) * (11-k);
}
rev = 11 - ( add % 11 );
if( rev == 10 || rev == 11) {
rev = 0;
}
if( rev != parseInt(value.charAt(10),10) ) {
result = false;
}
if ( result ) {
input.parentNode.previousSibling.previousSibling.classList.remove('hide');
input.parentNode.nextSibling.nextSibling.classList.add('hide');
input.classList.remove('form_invalido');
input.classList.add('form_valido');
} else {
input.parentNode.previousSibling.previousSibling.classList.add('hide');
input.parentNode.nextSibling.nextSibling.classList.remove('hide');
input.classList.add('form_invalido');
input.classList.remove('form_valido');
}
}

simplify javascript code using regex (getting multiple links to iframes youtube)

Hi
I have a code which can show youtube videos if there are any links to youtube in the text
like for example the text which has multiple links
http://www.youtube.com/watch?v=-LiPMxFBLZY
testing
http://www.youtube.com/watch?v=Q3-l22b_Qg8&feature=related
example at:- pradyut.dyndns.org
the question has three parts which can be done using regex..
1 > getting the urls one by one for checking
2>checking if they youtube urls
3>converting the urls to youtube objects or iframes...
the second and the third are almost done with regex .. any improvements are welcome...
the most cumbersome is part one of the code which is to be done using regex...
this text i m forwarding to the function...
function to_youtubelink(text)
{
if ( text.indexOf ('<') > 0 || text.indexOf ('"') > 0 || text.indexOf ('>') > 0 )
return text;
else
{
var obj_text = new Array();
var oi = 0;
while(text.indexOf('http://') >=0)
{ //getting the paths
var si = text.indexOf('http://');
var gr = text.indexOf('\n', si);
var sp = text.indexOf(' ', si);
var ei;
if ( gr > 0 || sp > 0 )
{
if ( gr >0 && sp > 0 )
{
if ( gr < sp )
{
ei = gr ;
}
else
{
ei = sp ;
}
}
else if ( gr > 0)
{
ei = gr;
}
else
{
ei = sp;
}
}
else
{
ei = text.length;
}
var it = text.substring(si,ei);
if ( it.indexOf('"') > 0)
{
it.substring(0, it.indexOf('"') );
}
if(ei < 0)
ei = text.length;
else
ei = text.indexOf(' ', si) ;
obj_text[oi] = it;
text = text.replace( it, '[link_service]');
oi++;
}
var ob_text = new Array();
var ob =0;
for (oi=0; oi<obj_text.length; oi++)
{
if ( is_youtubelink( obj_text[oi] ) )
{
ob_text[ob] = to_utubelink(obj_text[oi]);
ob++;
}
}
oi = 0;
while ( text.indexOf('[link_service]') >=0 )
{
text = text.replace( '[link_service]', obj_text[oi]);
oi ++;
}
for (ob=0; ob<ob_text.length; ob++)
{
text = text +"\n\n" + ob_text[ob];
}
return text;
}
}
function is_youtubelink(text)
{
var matches = text.match(/http:\/\/(?:www\.)?youtube.*watch\?v=([a-zA-Z0-9\-_]+)/);
if (matches) {
return true;
} else {
return false;
}
}
function to_utubelink(text)
{
var video_id = text.split('v=')[1];
var ampersandPosition = video_id.indexOf('&');
if(ampersandPosition != -1)
{
video_id = video_id.substring(0, ampersandPosition);
}
text = "<iframe title=\"YouTube video player\" class=\"youtube-player\" type=\"text/html\" width=\"425\" height=\"350\" src=\"http://www.youtube.com/embed/" + video_id + "\" frameborder=\"0\"></iframe>"
return text;
}
now i m getting the output properly...
but i was thinking if the code could be done better and simplified using regex
...especially getting the urls part...
thanks
Try something like this:
/**
* Extracts a youtube id from a string
*
* #param string
*
* #return mixed
*/
function youtubeIDextract(text) {
var replace = "$1";
if (!text.match(/http:\/\/www\.youtube[^"]+/))
return false;
if (text.match(/^[^v]+v.([^&^=^\/]{11}).*/))
return text.replace(/^[^v]+v.([^&^=^\/]{11}).*/,replace);
else if (text.match(/^[^v]+\?v=([^&^=^\/]{11}).*/))
return text.replace(/^[^v]+\?v=([^&^=^\/]{11}).*/,replace);
else
return false;
}
A working example can be seen here: http://jsfiddle.net/6PRVp/2/
If you want to simply check if there is a youtube link in there somewhere, do this:
if (youtubeIDextract(text)) {...}
Notice that this also checks if there are 11 characters in the video id (without that, it would be a malformed youtube link).
Try this one:
function to_youtubelink(a) {
if (a.indexOf("<") > 0 || a.indexOf('"') > 0 || a.indexOf(">") > 0) return a;
var b = Array(),
c = 0;
while (a.indexOf("http://") >= 0) {
var g, d = a.indexOf("http://"),
e = a.indexOf("\n", d),
f = a.indexOf(" ", d);
g = e > 0 || f > 0 ? e > 0 && f > 0 ? f > e ? e : f : e > 0 ? e : f : a.length;
var h = a.substring(d, g);
h.indexOf('"') > 0 && h.substring(0, h.indexOf('"')), g = 0 > g ? a.length : a.indexOf(" ", d), b[c] = h, a = a.replace(h, "[link_service]"), c++
}
var i = Array(),
j = 0;
for (c = 0; b.length > c; c++) is_youtubelink(b[c]) && (i[j] = to_utubelink(b[c]), j++);
c = 0;
while (a.indexOf("[link_service]") >= 0) a = a.replace("[link_service]", b[c]), c++;
for (j = 0; i.length > j; j++) a = a + "\n\n" + i[j];
return a
}
function is_youtubelink(a) {
var b = a.match(/http:\/\/(?:www\.)?youtube.*watch\?v=([a-zA-Z0-9\-_]+)/);
return b ? !0 : !1
}
function to_utubelink(a) {
var b = a.split("v=")[1],
c = b.indexOf("&");
return c != -1 && (b = b.substring(0, c)), a = '<iframe title="YouTube video player" class="youtube-player" type="text/html" width="425" height="350" src="http://www.youtube.com/embed/' + b + '" frameborder="0"></iframe>'
}

Categories

Resources