Javascript .replace() / regex with code as string - javascript

I'm trying to "remove" (just replace it with "") the following String:
<script type="text/javascript">
document.createElement("img").src="http://www.google.com"
</script>
From the following String:
<SCRIPT LANGUAGE=JavaScript>
var PAswf = "_ADPATH_[%SWF File%]";
var advurl = "_ADCLICK_";
var PAadvurl = escape(advurl);
var PAwidth = "[%Width%]";
var PAheight = "[%Height%]";
var wmValue = "_ADDCP(wm)_";
if (!wmValue)wmValue = "opaque";
var PAwmode = wmValue;
document.write('<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"');
document.write(' WIDTH="'+ PAwidth +'" HEIGHT="'+ PAheight +'">');
document.write('<PARAM NAME=movie VAL'+'UE="' + PAswf + '?clickTag='+ PAadvurl +'"><PARAM NAME=quality VALUE=high><PARAM NAME=wmode VALUE='+ PAwmode +'>');
document.write('<EMBED sr'+'c="'+PAswf + '?clickTag='+ PAadvurl +'" quality=high wmode='+ PAwmode);
document.write(' swLiveConnect=TRUE WIDTH="'+ PAwidth +'" HEIGHT="'+ PAheight +'"');
document.write(' TYPE="application/x-shockwave-flash">');
document.write('</EMBED></OBJECT>');
</SCRIPT>
<script type="text/javascript">
document.createElement("img").src="http://www.google.com"
</script>
As you can see, the String is at the bottom of the code block, but that shouldn't really matter. I've stored the first string as a variable, codeString, and tried the following.
// code refers to the bigger code string
code.replace(/codeString/gm, "");
Doesn't seem to match. I'm sure I'm doing something wildly wrong, but I've searched for about an hour and have come up empty. Any ideas?

/codeString/ is a regular expression searching for the literal "codeString", not a variable containing a pattern. Also, string.replace(pattern, replacement) does not modify string but returns a new string with the replacement applied.
You do not need a regular expression for stripping fixed strings like this, the next code will remove the string once from code:
var codeString = '<script type="text/javascript">\n' +
'document.createElement("img").src="http://www.google.com"\n' +
'<\/script>';
code = code.replace(codeString, "");

Well you can start with
code.replace(codestring, "");
If it needs to be a regular expression, you can use:
code.replace(new RegExp(codestring, "gm"), "");
but be aware that the regex metacharacters should be escaped with backslashes.

Related

How To Print Variable Data And String By Adding Inside Single Quotes

How To Output Variable data And String With Single Quotes.I Want To Add String After The Value Of mo.Output Should Be Inside Single Quotes.
Output Should Be:- '123target'
<button value="123" class="btn">Button 1</button>
$('.btn').click(function(){
var mo = $(this).val();
var re = '''+mo+'target'';
document.write(re);
});
Use double quote to wrap or escape it using \.
var re = '\'' + mo + 'target\'';
// or
var re = "'" + mo + "target'";
Try this,
$('.btn').click(function(){
var mo = $(this).val();
var re = "'"+mo + "target'";
document.write(re);
});
Check jsfiddle link.
You haven't kept quotes properly.
$('.btn').click(function() {
var mo = $(this).val();
var re = "'" + mo + "target'";
document.write(re);
});
<button value="123" class="btn">Button 1</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
additionally you can also use ES6 template strings (backtics)
var mo = "quotes"
out.innerHTML=`some string in 'single ${mo}' and some in "double ${mo}" and also some "mix'd ${mo} content"`
<div id="out"></div>

li append function not work

I'm using blogger as my blogging platform. In my blog homepage, I create a function to grab all images from single post for each post (there are 5 posts in my homepage), then append all images from single post to single slider, for each post.
This is my function script (I place it after <body> tag):
<script type='text/javascript'>
//<![CDATA[
function stripTags(s, n) {
return s.replace(/<.*?>/ig, "")
.split(/\s+/)
.slice(0, n - 1)
.join(" ")
}
function rm(a) {
var p = document.getElementById(a);
img = p.getElementsByTagName("img").each( function(){
$(".flexslider .slides").append($("<li>").append(this));
});
p.innerHTML = '<div class="entry-container"><div class="entry-content"><div class="entry-image"><div class='flexslider'><ul class='slides'></ul></div></div><div class="entry-header"><h1>' + x + '</h1></div><p>' + stripTags(p.innerHTML, SNIPPET_COUNT) + '</p></div></div>'
}
//]]>
</script>
Then my variable, each post have single variable, different for each post based on it's ID:
<script type='text/javascript'>var x="Post Title",y="http://myblog.url/post-url.html";rm("p8304387062855771110")
My single post markup:
<span id='p8304387062855771110'></span>
The problem is, the append function in my script not work. Am I forget something in my code?
Your jQuery/JavaScript is very ropey. There is no method each on a nodelist. Try not to mix jQuery/JavaScript up so much. And you might consider using a array/join on the html you want to insert to keep the line length readable. That way you might have noticed that your HTML quotes were not consistent.1
var $p = $('#' + a);
$p.find('img').each(function () {
var html = $('<li>').append($(this))
$('.flexslider .slides').append(html);
});
var html = [
'<div class="entry-container"><div class="entry-content">',
'<div class="entry-image"><div class="flexslider">',
'<ul class="slides"></ul></div></div><div class="entry-header">',
'<h1><a href="',
y,
'">',
x,
'</a></h1></div><p>',
stripTags(p.innerHTML, SNIPPET_COUNT),
'</p></div></div>'
].join('');
$p.html(html);
1 Personally I prefer single quotes for JS work and double quotes for HTML attributes and never the twain shall meet.
I think <li> doesnt work try li like this:
$(".flexslider .slides").append($("li").append(this));
You could get rid of type="text/javascript" and //<![CDATA[, it is 2014, after all ;-)
Also, .*? is not what you mean.
<script>
function stripTags(s, n) {
return s.replace(/<[^>]*>/g, "") // Be careful with .*? : it is not correct
.split(/\s+/)
.slice(0, n - 1)
.join(" ")
}
function rm(id) {
var $p = $('#' + id);
img = $p.find("img").each( function(){
$(".flexslider .slides").append($("<li>").append(this));
});
p.innerHTML = '<div class="entry-container"><div class="entry-content"><div class="entry-image"><div class="flexslider"><ul class="slides"></ul></div></div><div class="entry-header"><h1>' + x + '</h1></div><p>' + stripTags(p.innerHTML, SNIPPET_COUNT) + '</p></div></div>'
}
</script>

case insensitive word boundaries with regExp

for some reason the gi modifier is behaving as case sensitive. Not sure what's going on, but maybe someone knows why this is. it works fine when the cases are the same. This JSFiddle will demonstrate my problem. Code below. Thanks.
javaScript:
var search_value = $('#search').val();
var search_regexp = new RegExp(search_value, "gi");
$('.searchable').each(function(){
var newText =(this).html().replace(search_value, "<span class = 'highlight'>" + search_value + "</span>");
$(this).html(newText);
});
HTML:
<input id = "search" value = "Red">
<div class = "searchable">this should be red</div>
<div class = "searchable">this should be Red</div>
Correct Code is
var search_value = $('#search').val();
var search_regexp = new RegExp(search_value, "gi");
$('.searchable').each(function(){
// var newText =$(this).html().replace(search_value, "<span class = 'highlight'>" + search_value + "</span>");
var newText =$(this).html().replace(search_regexp, function(matchRes) {
return "<span class = 'highlight'>" + matchRes + "</span>";
});
$(this).html(newText);
});
output
Fiddle
Issues with your code:-
First: search_regexp - You haven't used search_regexp anywhere in your code
Your Code
var newText =$(this).html().replace(search_value, "<span class = 'highlight'>" + search_value + "</span>");
Second
You are using search_value to replace. It will make both Red and red to either Red or red after replace.
eg: if search_value is Red then your output will be
this should be Red
this should be Red
you should use matched result instead of search_value
Third: How to use RegExp with replace function?
Correct Method is
var newText =$(this).html().replace(search_regexp, function(matchRes) {
return "<span class = 'highlight'>" + matchRes + "</span>";
});
Explanation
replace(<RegEx>, handler)
Your code isn't using your regex in the replace call, it's just using the search_value. This JSBin shows your code working: http://jsbin.com/toquz/1/
Do you actually want to replace the matches with the value (changing lowercase instances to uppercase in this example)? Using $.html() will also get you any markup within that element, so keep that in mind as well (in case there's a chance of having markup in the .searchable elements along with text.
Might be easier to do:
function highlight(term) {
var search_regexp = new RegExp(term, "gi");
$('.searchable').each(function(){
if (search_regexp.test($(this).html())) {
var highlighted = $(this).html().replace(search_regexp, function(m) {
return '<span class="highlight">'+m+'</span>';
});
$(this).html(highlighted);
}
});
}
Your original code in the JSBin is the highlightReplace() function.

JavaScript regex with URL activation along with smilies and more

I'm converting my PHP code for replacing smiley codes with images, activating links and a few other things to JavaScript.
Separately the functions work well, but together I'm getting the same problem as this. I think that this method is a bit overkill, I've used the following regex in PHP and it avoided conflicting with activated links
loop..
$message = preg_replace('#(?<!\w)'.$smiley.'(?!\w)#i', '<img src="images/smilies/'.$img.'" class="smiley" />', $message);
endloop
Is there any way to convert this regex to JavaScript valid rules? Thanks
Edit to clarify what/how I'm doing:
var input = 'HellO! :* :P ;P :-( http://google.com www.google.com';
//input = input.replace(/(\b(((https?|ftp|file):\/\/)|(www\.))[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%‌​=~_|])/ig,'$1');
var smilies = {
'sad.png': [':\(', ':-\('],
'kiss.png': [':\*', ':-\*', ';\*', ';-\*'],
'tongue.png': [':P', ':-P', ';P', ';-P']
};
for(var smiley in smilies) {
input = input.replace(new RegExp(smilies[smiley].join('|'), "gi"), '<img src="images/smilies/'+ smiley +'" class="smiley" />');
}
console.log(input);
Javascript doesn't support lookbehind so what you can do is to look for word boundary instead. Consider this code:
var re = new RegExp('\\b' + smiley + '(?!\\w)', 'gi');
message = message.replace(re, '<img src="images/smilies/' + img + '" class="smiley" />');
UPDATE:
Leaving input untouched, you can have your for loop like this which escapes every special character in input match:
for(var smiley in smilies) {
input = input.replace(new RegExp(smilies[smiley].join('|')
.replace(/[*()$]/g, '\\$&'), "gi"),
'<img src="images/smilies/'+ smiley +'" class="smiley" />');
}
OUTPUT:
"HellO! <img src="images/smilies/kiss.png" class="smiley" /> <img src="images/smilies/tongue.png" class="smiley" /> <img src="images/smilies/tongue.png" class="smiley" /> <img src="images/smilies/sad.png" class="smiley" /> http://google.com www.google.com"

punctuation marks in javascript

can you guys plese help me to correct the punctuation marks in the javascript below? Found error when i paste in visual studio. I'm not familiar with javascript! Thanks guy...
function showLocalImage(imgname) {
imgname = imgname.replace(/\\/g,”/”);
imgname = imgname.replace(/\’/g,”\\’”);
content = “<img src=\”" + String(imgname) + “\” border=\”0\” height=\”150\” weight=\”150\”>”;
eval(‘document.getElementById(“imagepreview”).innerHTML=\” + content +”‘”);
document.getElementById.imagepreview.style.visibility =’visible’;
}
This is because some of your quote characters are actually from a different character encoding, Use the following code:
function showLocalImage(imgname) {
imgname = imgname.replace(/\\/g,"/");
imgname = imgname.replace(/\’/g,"\\'");
content = "<img src=\"" + imgname + "\" border=\"0\" height=\"150\" weight=\"150\">";
var image_preview = document.getElementById("imagepreview");
image_preview.innerHTML = content;
image_preview.style.visibility = 'visible';
}
A couple of things:
You should reuse DOM result sets and elements as much as possible to avoid having to run a query against the DOM every time you need to reference an element or set of elements.
You should really try to avoid using the eval function as much as possible.
eval == EVIL
You seem to use wrong quote characters (” or ‘). Replace them with " or ' and you'll be good. Use an ascii text editor, not a word processor for typing.
You should avoid eval, and declare the content variable, as well as declare a reference to the imagepreview element:
function showLocalImage(imgname) {
imgname = imgname.replace(/\\/g,"/");
imgname = imgname.replace(/\'/g,"\\'"); //Is this really necessary?
var content = "<img src=\"" + imgname + "\" border=\"0\" height=\"150\" weight=\"150\">";
var img = document.getElementById("imagepreview");
img.innerHTML = content;
img.style.visibility ='visible';
}

Categories

Resources