regex if else statement failing - javascript

here's a function that checks if there's a link in text (if so, replaces it with a clickable one)
example:
The actual resolution of this image is 3067x2276, not 4381x3251. See this page for information on how to find out what the resolution of an image is.
function getTopComment(permalink) {
var fullLink = "https://www.reddit.com" + permalink + ".json?sort=top";
$.getJSON(fullLink, function foo(result) {
var rawComment = result[1].data.children[0].data.body;
var regExp = /\[(.*?)\]\(([^\)]+)\)/g;
var matches = regExp.exec(rawComment);
if (matches.length > 2) {
var replace = `${matches[1]}`;
var cleanComment = rawComment.replace(matches[0], replace);
$("#text").append('<p>' + cleanComment + '</p>');
} else {
$("#text").append('<p>hello</p>');
}
});
}
<body>
<div class="container">
<div id="art" class="img column1">
</div>
<div id="text" class="comment column2">
</div>
</div>
</body>
I tried running it on chrome's javascript console, replacing $("#text").append... with console.log("hello"), and it works. Why does it not work on jsfiddle?

use try and catch instead
function getTopComment(permalink) {
var fullLink = "https://www.reddit.com" + permalink + ".json?sort=top";
$.getJSON(fullLink, function foo(result) {
var rawComment = result[1].data.children[0].data.body;
try {
var regExp = /\[(.*?)\]\(([^\)]+)\)/g;
var matches = regExp.exec(rawComment);
var replace = `${matches[1]}`;
var cleanComment = rawComment.replace(matches[0], replace);
$("#text").append('<p>' + cleanComment + '</p>');
} catch(err) {
$("#text").append('<p>' + rawComment + '</p>');
}
});
}

exec returns null if regex not matched result. Just check it at first.
...
if (matches && matches.length > 2) {
...

Related

JavaScript: Function that accepts message and replaces specific characters to line of code?

I have a chat application on Node.js, I just made smileys for it.
How can I scan/replace all sets of characters in messages to line of code? (image)
here is the message being added to chat window.
$("#chatEntries").append('<div class="messagesOLD">' +
"<span class='msg_date'>"+dateFormat(time)+"</span><span class='msg_seperator'> | </span><span class='msg_name'>"+ pseudo + '</span> : ' + replaceEmoticons(msg) + '</div>');
msg is actual message, and replaceEmoticons is function name but it's blank for now as I don't know how to implement it.
Here are my smileys:
var smileys = [];
smileys[":/"] = "derp.png";
smileys[":)"] = "happy.png";
smileys[":D"] = "laugh.png";
smileys[":3"] = "meow.png";
smileys[":{"] = "must.png";
smileys[":V"] = "pac.png";
smileys[":("] = "sad.png";
smileys[":O"] = "surprised.png";
smileys[":?"] = "wat.png";
The array/object names are the actual char sets I want to be replaced in message.
All smileys are located like: http://example.com/public/images/smileys/
In the end I want all messages to look like:
Hello how are you all doing today? :D
would become:
Hello how are you all doing today? <img src='http://example.com/public/images/smileys/laugh.png' id='chat_smls'/>
Update:
It needs to replace only character sets when there is space before and after them.
So:
Hello:D = Not valid. Hello:DHow = Not Valid Hello :DHow = Not Valid Hello :D How = Valid.
Simply call replace :
function replaceEmoticons(str) {
for (var key in smileys) {
var re = new RegExp("(?:^|\\s)" + key.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&") + "(?=$|\\s)", 'g');
str = str.replace(re, "<img src='http://example.com/public/images/smileys/" + smileys[key] + "' id='chat_smls'/>");
}
return (str);
}
Here is a demo :
var smileys = [];
smileys[":/"] = "derp.png";
smileys[":)"] = "happy.png";
smileys[":D"] = "laugh.png";
smileys[":3"] = "meow.png";
smileys[":{"] = "must.png";
smileys[":V"] = "pac.png";
smileys[":("] = "sad.png";
smileys[":O"] = "surprised.png";
smileys[":?"] = "wat.png";
function RegExpEscape(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
function replaceEmoticons(str) {
for (var key in smileys) {
var re = new RegExp("(?:^|\\s)" + RegExpEscape(key) + "(?=$|\\s)", 'g');
str = str.replace(re, "<img src='http://example.com/public/images/smileys/" + smileys[key] + "' id='chat_smls'/>");
}
return (str);
}
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
update();
function update() {
$('#result').text(replaceEmoticons($('#input').val()));
}
$('#input').keyup(function () {
delay(update, 250);
});
textarea
{
width: 100%;
height: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h4>Input :</h4>
<textarea id="input">
Hello how are you all doing today? :D
</textarea>
<hr>
<h4>Result :</h4>
<textarea id="result">
</textarea>
Edited to fulfill requirements

Ajax change text on page

Hello i have some html like this:
<div class="col-md-4" id="sk6x4">
<a href="/razbornye/models6x4/sk6x4">
<span class="sceneName">СК6x4</span> <span class="scenePrice">671 384p.</span></a>
</div>
<div class="col-md-4" id="sk6x4">
<a href="/razbornye/models6x4/sk6x4">
<span class="sceneName">СК6x4</span> <span class="scenePrice">671 384p.</span></a>
</div>
<div class="col-md-4" id="sk6x4">
<a href="/razbornye/models6x4/sk6x4">
<span class="sceneName">СК6x4</span> <span class="scenePrice">671 384p.</span></a>
</div>
And some JS:
jQuery(document).ready(function($) {
var col = $('.preview').find('.col-md-4 .sceneName');
var urls = [];
var ids = [];
col.each(function(i) {
var yy = $(this).closest('.col-md-4').find('a').attr('href');
var xx = $(this).closest('.col-md-4').attr('id');
urls.push(yy);
ids.push(xx);
});
var dataUrls = function() {
$.each(urls, function (i, url) {
$.ajax({
url: url,
type: 'POST',
success: function (data) {
var apronFactor = (($(data).find('.table.table-bordered tr:eq(6) td:eq(2)').text()).replace(/\s+/g, ''))*1;
var apronPrice = ($(data).find('.table.table-bordered tr:eq(6) td:eq(3)').text()).replace(/\s+/g, '');
var apronPriceMR = apronPrice.substring(0, apronPrice.length - 2);
var apronPriceToNum = apronPriceMR*1;
var apronTotalPrice = apronFactor * apronPriceToNum;
/**/
var plankFactor = (($(data).find('.table.table-bordered tr:eq(7) td:eq(2)').text()).replace(/\s+/g, ''))*1;
var plankPrice = ($(data).find('.table.table-bordered tr:eq(7) td:eq(3)').text()).replace(/\s+/g, '');
var plankPriceMR = plankPrice.substring(0, plankPrice.length - 2);
var plankPriceToNum = plankPriceMR*1;
var plankTotalPrice = plankFactor * plankPriceToNum;
/**/
var tentFactor = (($(data).find('.table.table-bordered tr:eq(8) td:eq(2)').text()).replace(/\s+/g, ''))*1;
var tentPrice = ($(data).find('.table.table-bordered tr:eq(8) td:eq(3)').text()).replace(/\s+/g, '');
var tentPriceMR = tentPrice.substring(0, tentPrice.length - 2);
var tentPriceToNum = tentPriceMR*1;
var tentTotalPrice = tentFactor * tentPriceToNum;
/**/
var totalOptionsPrice = apronTotalPrice + plankTotalPrice + tentTotalPrice;
/**/
var complexWithoutOptionsPrice = ($(data).find('#cel_1 > .value').text()).replace(/\s+/g, ''); //cWOP
var cWOPMR = complexWithoutOptionsPrice.substring(0, complexWithoutOptionsPrice.length - 2);
var cWOPToNum = cWOPMR * 1;
/**/
var newTotalPrice = cWOPToNum + totalOptionsPrice;
var newTotalPriceToString = newTotalPrice.toString().replace(/\B(?=(\d{3})+(?!\d))/g, " ") + "р.";
$(ids[i] + ' .scenePrice').text(newTotalPriceToString));
}
});
});
}
dataUrls();
});
The task is:
Take prices from another page and replace price on this page
The problem is
$(ids[i] + ' .scenePrice').text(newTotalPriceToString));
It's not work.
Replace this line:
$(ids[i] + ' .scenePrice').text(newTotalPriceToString));
With:
$('#'+ids[i] + ' .scenePrice').text(newTotalPriceToString));
I guess you are just passing the string of id but not # along with it.
try to find out why is problematic line not working:
alert(ids[i] + ' .scenePrice'); //check whether your selector is correct
alert($(ids[i] + ' .scenePrice').length); //check whether jQuery matched element
But from the look at your code, you are probably just missing '#' in front of id.

javascript array to string conversion

I have this array in javascript:
[div.parts, div.editor, div.inside-1, div.container-2, div.inside-wrapper, div#content, div.whitebgpan, div, div#maindiv, body, html]
How can I convert it into string, so that the output will be:
div.parts div.editor div.inside-1 div.container-2 div.inside-wrapper div#content div.whitebgpan div div#maindiv body html
here is my code:
jQuery(document).on('click', function(e){
var ClickedParents = jQuery(e.target).parents(); //Get all parents of clicked element
var ClickedParents_array = jQuery.makeArray(ClickedParents); //Make array
console.log(ClickedParents_array); //Show output in colsole
});
You can use a combination of the jQuery each function and JavaScript's Array.Join function to solve this problem.
DEMO: http://jsfiddle.net/zay015ex/1/
I've artificially retrieved an array of jQuery objects to show how you can solve this, but the concept is common to your problem.
HTML
<div id="parent">
<div id="child1"></div>
<div id="child2"></div>
<div id="child3"></div>
<div id="child4"></div>
<div id="child5"></div>
</div>
JavaScript
var arrayOfObjects = $('#parent').children();
var ids = [];
$.each(arrayOfObjects, function(i, val)
{
ids.push(val.id);
});
var idString = ids.join(' ');
You can read up more on the jQuery each function here.
You can read up more on the JavaScript's Array.Join function
here.
===== Update =====
Ok, the following code is tested, just open a console and paste this. it selects all div tags and convert into selector string.
$.map($('div'),function toSelector(elem){
var jqObj = $(elem)
var tag = jqObj.prop('tagName').toLowerCase()
var classes = jqObj.attr('class') ? '.' + jqObj.attr('class').split(' ').join('.') : ''
var ids = jqObj.attr('id') ? '#' + jqObj.attr('id').split(' ').join('#'): ''
return tag + classes + ids
})
===================
Supposing they're jquery objects, you have to build the string manually.
For example, do something like following. (not tested)
function toSelector(jqObj){
var tag = jqObj.prop('tagName').toLowerCase()
var classes = jqObj.attr('class') ? '.' + jqObj.attr('class').split(' ').join('.') : ''
var ids = jqObj.attr('id') ? '#' + jqObj.attr('id').split(' ').join('#'): ''
return tag + classes + ids
}
array.map(toSelector)
I think below code is helpful for you.
<script type="text/javascript">
String.prototype.replaceAll = function ( token, newToken, ignoreCase ) {
var _token;
var str = this + "";
var i = -1;
if ( typeof token === "string" ) {
if ( ignoreCase ) {
_token = token.toLowerCase();
while( (
i = str.toLowerCase().indexOf(
token, i >= 0 ? i + newToken.length : 0
) ) !== -1
) {
str = str.substring( 0, i ) +
newToken +
str.substring( i + token.length );
}
} else {
return this.split( token ).join( newToken );
}
}
return str;
};
try{
var arr = [];
arr.push('div.parts', 'div.editor', 'div.inside-1', 'div.container-2', 'div.inside-wrapper', 'div#content', 'div.whitebgpan', 'div', 'div#maindiv', 'body', 'html');
var stringData = arr.toString();
stringData = stringData.replaceAll(",", " ");
console.log(stringData);
}catch(e){
alert(e)
}
</script>

function is not working in my code

my problem is that text3 is undefined in my codes in here:
t += text2 + "Case #" + i + ":" + "<br>" + text3 + "<br>";
but it is here:
$('#pass').keyup(function (e) {
var strong = new RegExp("^(?=.{11,})(((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[a-z])(?=.*\\W))|((?=.*[a-z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]))).*$", "g");
var normal = new RegExp("^(?=.{4,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[a-z])(?=.*\\W))|((?=.*[0-9])(?=.*\\W))).*$", "g");
if (strong.test($(this).val())) {
text3 = "strong";
} else if (normal.test($(this).val())) {
text3 = "normal";
} else {
text3 = "weak";
}
return true;
});
here is all of my code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<p><input placeholder="number of tests" type="text" name="numbers" id="x"/></p>
<div id="passdiv"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$('#x').keyup(function (e) {
var i;
var text2 = '';
var t = "";
var x = document.getElementById("x").value;
for (i = 1; i <= x; i++) {
text2 = '<p><input placeholder="test NO. ' + i + '" type="password" id="pass" /></p>';
t += text2 + "Case #" + i + ":" + "<br>" + text3 + "<br>";
}
document.getElementById("passdiv").innerHTML = t;
return true;
});
$('#pass').keyup(function (e) {
var strong = new RegExp("^(?=.{11,})(((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[a-z])(?=.*\\W))|((?=.*[a-z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]))).*$", "g");
var normal = new RegExp("^(?=.{4,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[a-z])(?=.*\\W))|((?=.*[0-9])(?=.*\\W))).*$", "g");
if (strong.test($(this).val())) {
text3 = "strong";
} else if (normal.test($(this).val())) {
text3 = "normal";
} else {
text3 = "weak";
}
return true;
});
</script>
</body>
</html>
what is the problem?
please help
Looks like $('#x').keyup() is being called before $('#pass').keyup()
Your call $('#x').keyup(function (e) { is creating the first event listener so on keyup you will always endup with text3 is undefined because the $('#pass').keyup(function (e) { will be triggered always later.
EDIT:
Your second keyup handler will never work because it will grab the #pass element only once (during document parse). You need to create some defered listener to fix it.
// Anyway this won't fix your text3 is undefined problem.
What you need to do is define it first before the two .keyup handlers.
NOTE:
But please avoid setting global variables anyway ;)
Put everything into a closure or something.
Last but not least DO NOT create many elements with the same ID this is a major bug.
Look, even after fixing the code to get it to work it makes very little sense. Using roryok's jsFiddle, it'll only work if the value you're entering is a number and doing so just spawns the paragraph elements for the number you entered. You can enter as many numbers as you'd like (before your browser crashes), it'll always return as "weak".
If it's a simple password strength meter you're after, unless you can explain the logic you're trying to achieve more by forcing it to stick to numbers, I'd dump most of the JavaScript code and reduce it to
$('#x').keyup(function (e) {
document.getElementById("passdiv").innerHTML = strength($(this).val());
return true;
});
function strength(val) {
var strong = new RegExp("^(?=.{11,})(((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[a-z])(?=.*\\W))|((?=.*[a-z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]))).*$", "g");
var normal = new RegExp("^(?=.{4,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[a-z])(?=.*\\W))|((?=.*[0-9])(?=.*\\W))).*$", "g");
if (strong.test(val)) {
t = "strong";
} else if (normal.test(val)) {
t = "normal";
} else {
t = "weak";
}
return t;
}
This will then validate the whole input each time you enter a character, which the user can then submit once it's "strong".
Here's my jsFiddle: http://jsfiddle.net/xqooj482/
text3 is not set as a variable in your code, therefore it's always going to be undefined. You need to set it before your two functions.
Note: I also put things inside a jQuery ready function.
For some reason I'm being downvoted, but I tested this and it works
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<p><input placeholder="number of tests" type="text" name="numbers" id="x"/></p>
<div id="passdiv"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
// set text3 in here first
var text3 = "";
$('#x').keyup(function (e) {
var i;
var text2 = '';
var t = "";
var x = document.getElementById("x").value;
for (i = 1; i <= x; i++) {
text2 = '<p><input placeholder="test NO. ' + i + '" type="password" id="pass" /></p>';
t += text2 + "Case #" + i + ":" + "<br>" + text3 + "<br>";
}
document.getElementById("passdiv").innerHTML = t;
return true;
});
$('#pass').keyup(function (e) {
var strong = new RegExp("^(?=.{11,})(((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[a-z])(?=.*\\W))|((?=.*[a-z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]))).*$", "g");
var normal = new RegExp("^(?=.{4,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[a-z])(?=.*\\W))|((?=.*[0-9])(?=.*\\W))).*$", "g");
if (strong.test($(this).val())) {
text3 = "strong";
} else if (normal.test($(this).val())) {
text3 = "normal";
} else {
text3 = "weak";
}
return true;
});
});
</script>
</body>
</html>
Also here's a fiddle of it working
http://jsfiddle.net/gsuy4t27/

Find the string occurence and wrap it with a span

<div id="wrapper">
<div>if(true)<span class="openParen bm1">{</span></div>
<div>cout<<"hey";cin>>x;</div>
<div><span class="closeParen bm1>}</span></div>
</div>
I wanted to find cout using regex, something like /cout[^;]*;/ and then wrap it with a span.
<div id="wrapper">
<div>if(true)<span class="openParen bm1">{</span></div>
<div><span id="group">cout<<"hey";</span>cin>>x;</div>
<div><span class="closeParen bm1>}</span></div>
</div>
How will i find the regex occurence and the wrap it with a span? Anyone please?
UPDATE: I inserted cin>>x; after cout, cin shouldn't be wrapped.
I want to use something like this
text.replace(/(cout[^;]*;)/g, '<span class="group">$1</span>');
But i dont know how to apply it in DOM. anyone?
BUG for cin>> and cout<<, they cant be wrap until ; http://jsfiddle.net/3N4AE/11/
This is how you would apply the regex to your DOM using jQuery:
$('#wrapper div').filter(':contains("cout")').each(function () {
$(this).html($(this).text().replace(/(cout[^;]*;)/g, '<span class="group">$1</span>'));
});
Demo fiddle
update Regex way
DEMO
$('#wrapper div').filter(':contains("cout")').each(function () {
var x = $(this);
var txt = x.text();
x.html(txt.replace(/(cout[^;]*;)/g, '<span class="group">$1</span>'));
});
DEMO
var x =$('#wrapper div').filter(':contains("cout")');
var txt = x.text();
x.text('').append('<span id="group">'+txt+'</span>');
updated after OP updated question
DEMO
var x = $('#wrapper div').filter(':contains("cout")');
var txt = x.text();
x.text('');
var cout = txt.split(';');
$.each(cout, function (i, val) {
if (val.indexOf('cout') > -1) {
x.append('<span class="group">' + val + ';</span>');
} else {
x.append(val + ';');
}
});
update
DEMO
$('#wrapper div').filter(':contains("cout")').each(function () {
var x = $(this);
var txt = x.text();
x.text('');
var cout = txt.split(';');
$.each(cout, function (i, val) {
if (val.indexOf('cout') > -1) {
x.append('<span class="group">' + val + ';</span>');
} else {
x.append(val + ';');
}
});
});
updated after koala-dev comment
DEMO
$('#wrapper div').filter(':contains("cout")').each(function () {
var x = $(this);
var txt = x.text();
x.text('');
var cout = txt.split(';');
$.each(cout, function (i, val) {
if (val.indexOf('cout') > -1) {
x.append('<span class="group">' + val + ';</span>');
} else if ($.trim(val) != '') {
x.append(val + ';');
}
});
});
This should help
var pattern = /cout[^;]*;/;
var txt = $('#wrapper').find('div:nth-child(2)').text();
var el = $('#wrapper').find('div:nth-child(2)');
$(el).text("").append('<span id="group">' + txt + '</span');
jsfiddle

Categories

Resources