I'm fairly new to javascript so please go easy on me,
I have this code on a webpage:
<script type="text/javascript"> bb1 = "oldcode"; bb2 = "morecodehgere"; bb3 = 160000;</script>
I want to replace 1% of all page loads oldcode to newcode
There are multiple instances of this code on the same page and I want to replace them all.
window.onload = replaceScript;
function replaceScript() {
var randomNumber = Math.floor(Math.random()*101);
var toReplace = 'oldcode';
var replaceWith ='newcode';
if randomNumber == 1 {
document.body.innerHTML = document.body.innerHTML.replace(/toReplace/g, replaceWith);
}
}
This is the current code I've got but it doesn't work.
Is javascript the bast way to achieve what I'm looking to do? If so whats the best way to do this?
The regular expression literal:
/toReplace/g
will create a regular expression object that matches the string "toReplace". If you want to create a regular expression to match the (string) value of the variable toReplace, you must use the RegExp constructor:
var re = new RegExp(toReplace, 'g');
It is not a good idea to replace the innerHTML of the body with a copy of itself. The innerHTML property doesn't necessarily reflect all the nuances of the DOM and will not include things like dynamically added listeners. It also varies from browser to browser.
Using a regular expression to replace parts of innerHTML is almost certain to produce unpredictable results, it may work well on trivial pages but will not be reliable on complex pages.
Related
I'm trying to replace the word hello anywhere on the page with the word hi using Javascript. I created the script below however it isn't working how anticipated, is there something that I can do to achieve the outcome desired.
function(data) {
var newdata = data.replace("hello", "hi");
}
Jsfiddle
This will work, although might be overkill using regular expressions:
document.body.innerHTML = document.body.innerHTML.replace(/hello/g, "hi")
Jsfiddle
In your example, you are only replacing the first occurence.
Below the JavaScript documentation about replace:
Note: If you are replacing a value (and not a regular expression),
only the first instance of the value will be replaced. To replace all
occurrences of a specified value, use the global (g) modifier.
You have to use the global modifier as below
function(data) {
var newdata = data.replace(/hello/g,"hi");
}
I need to get a id from a html element and replace a part of the word. For example:
HTML
<input type="checkbox" id="facebookCheckbox"></div>
JavaScript
var x = document.getElementById("facebookCheckbox");
var name = x.id;
name.replace("Checkbox","");
This obviously does not work because the replacing word has to be standalone for it to be replaced. Is there a different way of doing this?
I'm looking for purely javascript no jQuery
Thank you!
name.replace("Checkbox","");
This obviously does not work because the replacing word has to be standalone for it to be replaced.
No, it does work and there's no need to be "standalone" - any part of the string can be matched. Only you did nothing with the result of the operation:
console.log(name.replace("Checkbox",""));
// or
name = name.replace("Checkbox","");
// or assign back to x.id maybe?
You are creating a copy of string when replacing, so you must assign the result of .replace() back to x.id.
var x = document.getElementById("facebookCheckbox");
x.id = x.id.replace("Checkbox","");
this is not going to work in this way. However you can have a marker kind of character by which you can break the name into array and implement the logic. For example:
var x = document.getElementById("facebook_Checkbox");
//Note I have added underscore in the Id
var name = x.id;
var arr=name.split("_");
//Now you have Checkbox and Facebook as string objects (part of array) and you can use them
name=arr[0]
I hope it will solve the purpose.
I am trying to create a very simplistic XSS detection system for a system I am currently developing. The system as it stands, allows users to submit posts with javascript embedded within the message. Here is what I currently have:-
var checkFor = "<script>";
alert(checkFor.indexOf("<script>") !== -1);
This doesn't really work that well at all. I need to write code that incorporates an array which contains the terms I am searching for [e.g - "<script>","</script>","alert("]
Any suggestions as to how this could be achieved using JavaScript/jQuery.
Thanks for checking this out. Many thanks :)
Replacing characters is a very fragile way to avoid XSS. (There are dozens of ways to get < in without typing the character -- like < Instead, HTML-encode your data. I use these functions:
var encode = function (data) {
var result = data;
if (data) {
result = $("<div />").html(data).text();
}
};
var decode = function (data) {
var result = data;
if (data) {
result = $("<div />").text(data).html();
}
};
As Explosion Pills said, if you're looking for cross–site exploits, you're probably best to either find one that's already been written or someone who can write one for you.
Anyway, to answer the question, regular expressions are not appropriate for parsing markup. If you have an HTML parser (client side is easy, server a little more difficult) you could insert the text as the innerHTML of an new element, then see if there are any child elements:
function mightBeMarkup(s) {
var d = document.createElement('div');
d.innerHTML = s;
return !!(d.getElementsByTagName('*').length);
}
Of course there still might be markup in the text, just that it's invalid so doesn't create elements. But combined with some other text, it might be valid markup.
The most effective way to prevent xss attacks is by replacing all <, > and & characters with
<, >, and &.
There is a javascript library from OWASP. I haven't worked with it yet so can't tell you anything about the quality. Here is the link: https://www.owasp.org/index.php/ESAPI_JavaScript_Readme
So let’s say the text KEYWORDANIMAL:(Cat) appears on a page. I want to search through the page for all instances of KEYWORDANIMAL, and then pull the actual animal, in this case Cat, into a variable to be used in another script that’ll pull in related content. I also want to replace KEYWORDANIMAL:(Cat) with an empty div with concatenated ID to be targeted by the other script (this other script is already working fine by itself).
I've been using info from several other threads here but just cannot make it all come together.
-Find text string using jQuery?
-Get text from character and after using jQuery
-How do I use JQuery to replace all occurring of a certain word in a webpage?
Here's what I have so far:
<p>Here is an animal: KEYWORDANIMAL(Cat)</p>
var findString = $('p:contains("KEYWORDANIMAL")').html();
var startIDString = findString.indexOf('(') + 1;
var endIDString = findString.indexOf(')');
var animalID = findString.substring(startIDString, endIDString);
var embedString1 = "<div id=\"";
var embedString2 = "\"></div>";
var embedStringFull = embedString1 + "animal" + animalID + embedString2;
alert(embedStringFull);
findString.each(function () {
var newDIV = $(this).html().replace('KEYWORDANIMAL', embedStringFull);
$(this).html(newDIV);
});
In fiddle form: http://jsfiddle.net/dC6bj/1/
I got the find part down (probably not very efficiently though), but I am clearly missing something on the replace.
If you absolutely have to do this with JavaScript, you can use a regex replacement function:
var animal_regex = /KEYWORDANIMAL\((.*?)\)/g;
$('p:contains("KEYWORDANIMAL")').each(function() {
var $this = $(this);
var html = $this.html().replace(animal_regex, function(match, name) {
return '<div id="animal' + name + '"></div>';
});
$this.html(html);
});
Demo: http://jsfiddle.net/dnuaL/
This should be done serverside, if possible.
For your third question on how toreplace all occurences of a certain word in a webpage use Regex.Replace like this:
var pagecontent = $('body').html();
var newcontent = Regex.Replace(pagecontent , #"[cat]", "dog");
&('body').html(newcontent);
Regex is the fastest solution for this kind of stuff.
My code example is a bit simple, it would also replace ocurrences within a tag.
or within a word for example in catamaran or .
To make it more perfect you could look for cat preceded by a space and followed by a space or a point or a comma. Read some regex tutorials for this. (It's really worth learning, once you know how to, you'll use it a lot)
Goodluck!
I can use the getElementsByTagName() function to get a collection of elements from an element in a web page.
I would like to be able to use a similar function on the contents of a javascript string variable instead of the contents of a DOM element.
How do I do this?
EDIT
I can do this by creating an element on the fly.
var myElement = new Element('div');
myElement.innerHTML = "<strong>hello</strong><em>there</em><strong>hot stuff</strong>";
var emCollection = myElement.getElementsByTagName('em');
alert(emCollection.length); // This gives 1
But creating an element on the fly for the convenience of using the getElementsByTagName() function just doesn't seem right and doesn't work with elements in Internet Explorer.
Injecting the string into DOM, as you have shown, is the easiest, most reliable way to do this. If you operate on a string, you will have to take into account all the possible escaping scenarios that would make something that looks like a tag not actually be a tag.
For example, you could have
<button value="<em>"/>
<button value="</em>"/>
in your markup - if you treat it as a string, you may think you have an <em> tag in there, but in actuality, you only have two button tags.
By injecting into DOM via innerHTML you are taking advantage of the browser's built-in HTML parser, which is pretty darn fast. Doing the same via regular expression would be a pain, and browsers don't generally provide DOM like functionality for finding elements within strings.
One other thing you could try would be parsing the string as XML, but I suspect this would be more troublesome and slower than the DOM injection method.
function countTags(html, tagName) {
var matches = html.match(new RegExp("<" + tagName + "[\\s>]", "ig"));
return matches ? matches.length : 0;
}
alert(
countTags(
"<strong>hello</strong><em>there</em><strong>hot stuff</strong>",
"em"
)
); // 1
var domParser = new DOMParser();
var htmlString = "<strong>hello</strong><em>there</em><strong>hot stuff</strong>";
var docElement = domParser.parseFromString(htmlString, "text/html").documentElement;
var emCollection = docElement.getElementsByTagName("em");
for (var i = 0; i < emCollection.length; i++) {
console.log(emCollection[i]);
}
HTML in a string is nothing special. It's just text in a string. It needs to be parsed into a tree for it to be useful. This is why you need to create an element, then call getElementsByTagName on it, as you show in your example.