Javascript find and replace string within substring not using jquery - javascript

Hi can someone convert this jquery in to plain javascript?
$("body *").each(function () {
$(this).html($(this).html().replace(/\[br\]/\g,'<br/>'));
});
What it does is, it finds all [br] and then replace it with <br/>
The code above works perfectly in chrome but not in mozilla and IE so i need to execute it in plain javascript. many thanks to all!

Try this:
window.onload=function(){
document.body.innerHTML = document.body.innerHTML.replace( /\[br\]/g,'<br/>');
}
ps. In your code, there is a bug: instead of /\[br\]/\g should be /\[br\]/g

The problem was that you had an illegal character in your regular expression.
This works: $(this).html($(this).html().replace(/\[br\]/g,'<br/>'));
Live example: http://jsfiddle.net/tqksm/

the problem is not jQuery. You have first to take a reference to the current html content, then apply the replace and finally inject the new html:
$("body *").each(function () {
var $this = $(this);
var html = $this.html();
$this.html(html.replace(/\[br\]/\g,'<br/>'));
});

I think your missing the point here...rewriting it in plain Javascript is likely to only make it worse for you. One of jQuery's purposes is to take away all the pain that comes while writing Javascript that must work on all browser. So...I think you'd be best off if you start looking for an alternative approach on your jQuery code instead of rewriting it to plain Javascript.

Related

Javascript regex to replace ampersand in all links href on a page

I've been going through and trying to find an answer to this question that fits my need but either I'm too noob to make other use cases work, or their not specific enough for my case.
Basically I want to use javascript/jQuery to replace any and all ampersands (&) on a web page that may occur in a links href with just the word "and". I've tried a couple different versions of this with no luck
var link = $("a").attr('href');
link.replace(/&/g, "and");
Thank you
Your current code replaces the text of the element within the jQuery object, but does not update the element(s) in the DOM.
You can instead achieve what you need by providing a function to attr() which will be executed against all elements in the matched set. Try this:
$("a").attr('href', function(i, value) {
return value.replace(/&/g, "and");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
link
link
Sometimes when replacing &, I've found that even though I replaced &, I still have amp;. There is a fix to this:
var newUrl = "#Model.UrlToRedirect".replace(/&/gi, '%').replace(/%amp;/gi, '&');
With this solution you replace & twice and it will work. In my particular problem in an MVC app, window.location.href = #Model.UrlToRedirect, the url was already partially encoded and had a query string. I tried encoding/decoding, using Uri as the C# class, escape(), everything before coming up with this solution. The problem with using my above logic is other things could blow up the query string later. One solution is to put a hidden field or input on the form like this:
<input type="hidden" value="#Model.UrlToRedirect" id="url-redirect" />
then in your javascript:
window.location.href = document.getElementById("url-redirect").value;
in this way, javascript won't take the c# string and change it.

Using MVC resource in Jquery - function stops working

I have a Jquery function in MVC View that check if at least one checkbox is clicked. Function is working properly if I use hardcoded string. But when I add
#Resources.myString into, it stops working, I can't figure out why
$('.form-horizontal').on('submit', function (e) {
if ($("input[type=checkbox]:checked").length === 0) {
e.preventDefault();
alert("This is working");
alert(#Resources.myString); //with this the function is not working anymore
return false;
}
});
I need to add the the string for multilingual purpose.
I tried diferent aproches
alert(#Resources.myString);
alert(#Html.Raw(Resources.myString))
var aaa = { #Html.Raw(Resources.myString)} //and calling the aaa
I think I am missing some basic knowlage of how this should work together
During page rendering, #Resources.myString will be injected as is in the code. For instance, if myString == "abc";, you'll end up with alert(abc); which is not what you want.
Just try to enclose your string in quotes:
alert("#Resources.myString");
As an aside, putting Razor code in Javascript logic is usually considered bad practice, as it prevents you from putting Javascript code in separate files (and therefore caching), and makes the code less readable.
Take a look as this question and the provided answer which gives a simple way to deal with that.
As ASP.NET dynamically generates HTML, CSS, JS code, the best way to find the error is to read the generated sources (Ctrl + U in most modern browsers).
You will see that your code
alert(#Resources.myString);
produces
alert(yourStringContent);
and should result in a console error yourStringContent is not defined.
You need to use quotes as you are working with a JavaScript string:
alert('#Resources.myString');
It will produce a correct JavaScript code like:
alert('yourStringContent');

Trying to append html string fail with jQuery

I'm trying to append the following string to head with jQuery :
"<script type='text/javascript'> window['adrum-app-key'] = 'dummy';</script>"
But it always fails. Trying to do the same with 'Hello' string for example works as expected.
Following the code snippet I use to append the string :
var integrationScriptTag = handlebars.partials.integration(integrationData);
$(document).ready(function() {
$('head').append(integrationScriptTag.trim());
});
First string is the result of parsing integrationData.
Any help will really be appreciated.
Edit: I realize I misguided some of you with the first string. It is just a representation of what is produced by the first line of the second code snippet. So it doesn't really matter if it is some quote marks or not. The fact is I don't use a literal but rather a variable which is equal to the first string. I corrected the syntax so that there is no more confusion.
Here is the jsFiddle reproducing the problem.
jsFiddle
This should fix it:
'<script type=\'text/javascript\'> window[\'adrum-app-key\'] = \'dummy\';</script>'
or this would too:
'<script type="text/javascript"> window["adrum-app-key"] = "dummy";</script>'
Essentially you have quotes mismatch.
Use this, it will fix the issue
'<script type=\'text/javascript\'> window[\'adrum-app-key\'] =\'dummy\';<\/script>'
I finally found that you cannot append script tags to head with jQuery this way.
I found some solutions here and there (look at the first code snippet of the selected answer for the second link).
The head is parsed prior to the execution of javascript. So you probably have to perform the append outside the $(document).ready function.

Transform URL into a link unless there already was a link

I know this has been talked here, but no solutions were offer to the exact problem. Please, take a look...
I'm using a function to transform plain-text URLs into clickable links. This is what I have:
<script type='text/javascript' language='javascript'>
window.onload = autolink;
function autolink(text) {
var exp = /(\b(https?|ftp):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/gim;
document.body.innerHTML = document.body.innerHTML.replace(exp,"<a href='$1'>$1</a>");
}
</script>
This makes
https://stackoverflow.com/
Looks like:
https://stackoverflow.com/
It works, but also replace the existent HTML links with nested links.
So, a valid HTML link like
StackOverflow
Becomes something messy like:
StackOverflow">StackOverflow</a>...
How can I fix the expression to ignore the content of link tags? Thanks!
I'm a newbie... I barely understand the regex code. Please be gentle :) Thanks again.
Using the jQuery JavaScript library, this would look like (demo at http://jsfiddle.net/BRPRH/4):
function autolink() {
var exp = /(\b(https?|ftp):\/\/[-A-Z0-9+\u0026##\/%?=~_|!:,.;]*[-A-Z0-9+\u0026##\/%=~_|])/gi,
lt = '\u003c',
gt = '\u003e';
$('*:not(a, script, style, textarea)').contents().each(function() {
if (this.nodeType == Node.TEXT_NODE) {
var textNode = $(this);
var span = $(lt + 'span/' + gt).text(this.nodeValue);
span.html(span.html().replace(exp, lt + 'a href=\'$1\'' + gt + '$1' + lt + '/a' + gt));
textNode.replaceWith(span);
}
});
}
$(autolink);
Edit: Excluded textareas, scripts, and embedded CSS. I note that this can also be done using pure DOM's splitText, which has the advantage of not adding extra span elements.
Edit 2: Eliminated all ampersands and double quotes.
Edit 3: Got rid of < and > characters as well.
This problem is beyond the power of regular expressions. You might be able to write a regex that could avoid some links, but you wouldn't be able to avoid every existing link.
The good news is that a different approach will make the job much easier. Right now you using document.body.innerHTML to manipulate the HTML as plain text. To do it correctly that way, you will basically need to parse the HTML yourself. But you don't have to, because the browser has already parsed it for you!
The web browser allows you to access an HTML document as a series of object. It's called the Document Object Model (DOM) and if you do some reading on that, you should be able to learn how to traverse through the HTML, skipping over anything inside an A element, and using the regex you have on plain text only.

Escaping dilemma in Javascript

I have the following
var id='123';
newDiv.innerHTML = "";
Which renders in my HTML.
The problem I have is that I wish to take the call to the method TestFunction, and use as a string parameter in my function StepTwo(string, boolean), which would ideally end up in live HTML as shown...
notice how the TestFunction is a string here (it is executed within StepTwo using eval).
I have tried to format my JS as by :
newDiv.innerHTML = "";
but while this appears to me correct in my IDE, in the rendered HTML, it as garbelled beyond belief.
Would appreciate if anyone could point me in the right direction. Thanks!
One of the biggest capital failures on the internet is creating html in javascript by gluing strings together.
var mya = document.createElement("a");
mya.href="#";
mya.onclick = function(){
StepTwo(function(){
TestFunction('123', false );
}, true );
};
newDiv.innerHTML = "";
newDiv.appendChild(mya);
This Eliminates the need for any fancy escaping stuff.
( I probably should do 'onclick' differently, but this should work, I'm trying hard not to just use jQuery code to do everything )
Heres how I would do it in jQuery:
jQuery(function($){
var container = $("#container");
var link = document.createElement("a"); /* faster than $("<a></a>"); */
$(link).attr("href", "Something ( or # )" );
$(link).click( function(){
var doStepTwo = function()
{
TestFunction('123', true );
};
StepTwo( doStepTwo, false ); /* StepTwo -> doStepTwo -> TestFunction() */
});
container.append(link);
});
There is no good excuse for gluing strings together in Javascript
All it does is ADD overhead of html parsing back into dom structures, and ADD potential for XSS based broken HTML. Even beloved google get this wrong in some of their advertising scripts and have caused epic failures in many cases I have seen ( and they don't want to know about it )
I don't understand Javascript is the only excuse, and it's NOT a good one.
Try using " instead of \"
newDiv.innerHTML = "<a href="#"...
You should be using " not " or \" inside an HTML string quoted with double-quotes.
NewDiv.innerHTML = "";
There's probably a better way to do this - any time you find yourself using eval() you should stand back and look for a different solution.
You claim that eval is the right thing to do here. I'm not so sure.
Have you considered this approach:
and in your StepTwo function
function StepTwo(func,args,flag){
//do what ever you do with the flag
//instead of eval use the function.apply to call the function.
func.apply(args);
}
You could create the a element and attach to the click event using DOM Methods.
A Javascript Framework (like the ubiquitous jQuery) would make this a lot easier.
Your biggest problem is using eval, it leads to so many potential problems that it's nearly always better to find an alternative solution.
Your immediate problem is that what you really have is
as the next " after the start of the onclick attribute, closes it. Use " as others have suggested. And don't use eval.
You need to alternate your " and '.
Maybe you don't need quotes around the 123, because of Javascripts flexible typing. Pass it without quotes but treat it as a string within TestFunction.
Hey guys, thanks for all the answers. I find that the quot; seems to work best.
I'll give you guys some votes up once I get more reputation!
In regards to eval(), what you see in the question is a very small snapshot of the application being developed. I understand the woes of eval, however, this is one of those one in a million situations where it's the correct choice for the situation at hand.
It would be understood better if you could see what these functions do (have given them very generic names for stackoverflow).
Thanks again!
The best way is to create the element with document.createElement, but if you're not willing to, I guess you could do or use ".
In your code:
newDiv.innerHTML = "";
If it doesn't work, try changing "\'" to "\\'".
Remember that the " character is used to open and close the attribute on HTML tags. If you use it in the attribute's value, the browser will understand it as the close char.
Example:
<input type="text" value="foo"bar"> will end up being <input type="text" value="foo">.
...
I know this is hella' old now, but if anyone has issues with escaped strings when using eval (and you absolutely have to use eval), I've got a way to avoid problems.
var html = '';
eval('(function(div, html){div.innerHTML = html;})')(newDiv, html);
So, what's going on here?
eval creates a function that contains two parameters, div and html and returns it.
The function is immediately run with the parameters to the right of the eval function. This is basically like an IIFE.
In this case
var myNewMethod = eval('(function(div, html){div.innerHTML = html;})');
is basically the same as:
var myNewMethod = function(div, html){div.innerHTML = html;}
and then we're just doing this:
myNewMethod(newDiv, html); //where html had the string containing markup
I would suggest not using eval. If it can't be avoided, or if you control all the inputs and there's no risk of injection then this will help in cases where string escapes are an issue.
I also tend to use Function, but it isn't any more secure.
Here's the snippet I use:
var feval = function(code) {
return (new Function(code))();
}

Categories