Find and replace occurrence of string in whole html itself - javascript

Assume
<html>
<head>....</head>
<body>
.
. // Occurrences are here
.
</body>
</html>
I do
$(function()
{
$('html').html() = $('html').html().replace(/strToFind/g,'somethingElse');
});
in head, but it does't work. How I do to find and replace all occurrence of string in html document itself (not store in variable)?
Thanks

.html() is a function that returns the HTML, you can't assign to it. If you want to change the HTML of an object in jQuery, you put the new HTML as a parameter to the function:
$('html').html($('html').html().replace(/strToFind/g,'somethingElse'));

$('html').html() would return the html string , but won't set it.
You can use this function
function rep_all()
{
var str = $('html').html();
str.replace('strtofind','strtoreplace');
$('html').html(str);
}

.html() is something which writes on the html page it is not like variable so you can't assign anythig to it. you need to put the value inside it.like this:
$('html').html( $('html').html().replace(/strToFind/g,'somethingElse'));
see here:http://api.jquery.com/html/

It's been answered that the .html() is not assignable, you would have to pass the replaced content as a parameter.
Just to point out, it is very uncommon to replace the whole page's html content.
As you defined that the contents to be replaced are inside the body, you should at least (still not good) target only the body:
$('body').html($('body').html().replace(/strToFind/g,'somethingElse'))

Related

Regex in javascript replace function

Am newbie to regex am trying to do some regex replace function in java script here is my content and code
jQuery("td[headers='name_head']").each(function (index, value) {
var text = jQuery(this).html();
if( text.indexOf('<a href=') >= 0){
jQuery(this).text(text.replace(/<a href=.*\"$/, ""));
}
});
Html content will be look like this
Calculate Points
i just want to remove only the value inside href ""
Please throw some light on this
Regards
Sathish
The text() method just retrieves the text contents which doesn't include any HTML tags. You can use html() method with a callback function where you can get the old HTML content as the second argument to the callback and based on the old value generate updated HTML.
The better way is to update the href attribute value of a tag to empty by directly selecting them, there is no need to loop over them since all values need to be empty.
jQuery("td[headers='name_head'] a").attr('href', '');
UPDATE 1 : In case you want to iterate and do some operation based on condition then do something like this.
jQuery("td[headers='name_head'] a").each(function(){
if(//your ondition){
$(this).attr('href', '');
}
});
or
jQuery("td[headers='name_head']").each(function(){
if(//your ondition){
$('a', this).attr('href', '');
}
});
UPDATE 2 : If you want to remove the entire attribute then use removeAttr('href') method which removes the entire attribute itself.
jQuery("td[headers='name_head'] a").removeAttr('href');
Why would you reinvent the wheel?
You don't need regex to achieve this, you can simply do it this way:
jQuery("td[headers='name_head'] a").attr('href', '');
It will set href to "" for all <a> elements inside td[headers='name_head'] so it will always respect your condition.
I haven't tested this code; but something like this should help, don't think you need to use regex for this;
$('a.DisableItemLink[href!=''][href]').each(function(){
var href = $(this).attr('href');
// do something with href
})
This piece of code selects all elements which have the class DisableItemLink with a location set and sets it to blank.
I am curious as to what you are trying to do in the larger scheme of things though, sounds like there might be better ways to go about it.
Reference: some good selector combinations for links

Replace HTML between two tags

What I want to do is replace what is in between two HTML tags.
I'm using this as a reference but I'm still encountering problems:
REFERENCE
This is what I've tried:
el.getValue().replace(/<form.+<\/form>/, "<div></div>");
I need to replace all my form tags dynamically.
If you use jQuery, just retrieve the parent element of what you'd like to be replaced, and replace the content with the .html() function.
Ex:
var formParentElement = $('#formParentElement');
formParentElement.html("<div>my new content</div>");
If you don't use jQuery:
var formParentElement = document.getElementById("formParentElement");
formParentElement.innerHTML = "<div>my new content</div>";
The example assumes the parent element of your form has an ID with value "formParentElement".
Yeah. I found a solution.
el.getValue().replace(/<form[\s\S]*?<\/form>/, "<div></div>");
Explanation by #[James G]:
[\s\S]*? means [any character including space and line breaks]any number of times, and the ? makes the asterisk "not greedy," so it will stop (more quickly) when it finds </form>.
Reference

How do get contents of a p element one at a time

Using jQuery, I need to parse the contents of each <p> tag individually and then replace the text with the new text.
The code at the moment looks like:
str = $('p').text();
str = str.replace('yadayada','yada');
$('p').text(str);
This is currently getting the contents of all the <p> tags, concatenating them then replacing the massive block of text into each <p> which is close but not quite what I'd like it to do.
Is there a way to get the contents of each <p> block one at a time and replacing it with only it's contents? I do not know what ids or classes are being applied to them hence the need to use the generic tag.
Any help is much appreciated! :)
Use the text(fn)
A function returning the text content to set. Receives the index position of the element in the set and the old text value as arguments.
$('p').text(function(_ text){
return text.replace('yadayada','yada');
});
Use the text() version that accepts a callback as the second argument and return the replaced content from the callback
$('p').text(function(i, str) {
return str.replace('yadayada', 'yada');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>yadayada-1</p>
<p>yadayada-2</p>
<p>yadayada-3</p>
<p>4</p>
You can use .each method on the colletion:
$('p').each(function (pEl) {
var text = pEl.textContent;
});

Add code examples on your page with Javascript

I have a html code inside string
string_eng += '<b>Year Bonus</b> - bonus for each year</br></br>';
And I want to put this inside textarea, but when I do it, the result is:
- bonus for each year
It simply deletes all things inside the html tags. I just want to show all the code inside the string. I already tried <xmp>,<pre>, but none of them worked.
Thanks for any help.
EDIT.
Code with which I input data from the array to the textarea/code.
$('body').append('<code class="code_text"></code>');
for(var i=0; i<tag_list.length; i++){
var string='';
string+='---------------------------------------------------------------------------------\n';
string+='tag: '+tag_list[i][0]+'\n';
string+='nazwa_pl '+tag_list[i][1]+'\n';
string+='nazwa_eng '+tag_list[i][2]+'\n';
string+='tekst_pl '+tag_list[i][3]+'\n';
string+='tekst_eng '+tag_list[i][4]+'\n';
string+='\n\n\n';
$('.code_text').append(string);
}
I tried this using jsfiddle:
HTML
<textarea id="code"></textarea>
JavaScript
$(document).ready(function() {
var string_eng = '';
string_eng += '<b>Year Bonus</b> - bonus for each year</br></br>';
$("#code").html(string_eng);
});
Output (contained in textarea)
<b>Year Bonus</b> - bonus for each year</br></br>
Try it here: http://jsfiddle.net/UH53y/
It does not omit values held within tags, however if you were expecting the <b></b> tags to render as bold within the textarea, or the <br /> tags to render as line breaks, this wont happen either. textarea does not support formatting.
See this question for more information: HTML : How to retain formatting in textarea?
It's because you're using the jQuery .append method which seems to parse the string and insert it afterwards. I don't know jQuery at all, so there might be another special jQuery method, but here is a simple fix:
$('.code_text').append(document.createTextNode(string));
Edit:
I just read and tried the answer of Salman A. The "special jQuery method" exists and he used it. You can use this:
$('.code_text').text(string);

how to write <script> tag on javascript or jquery variable

this is the code i want to put in
var htm = "<center><div id="evp-8847b53dee625a133cfb02e88fd7bbf8-wrap" class="evp-video-wrap"></div><script type="text/javascript" src="http://convernet.evplayer.com/framework.php?div_id=evp-8847b53dee625a133cfb02e88fd7bbf8&id=Q29udmVybmV0L25ldyBjb252ZXJuZXQvVGhlIGZ1dHVyZS5tcDQ%3D&v=1333642408&profile=default"></script><script type="text/javascript"><!--
_evpInit('Q29udmVybmV0L25ldyBjb252ZXJuZXQvVGhlIGZ1dHVyZS5tcDQ=[evp-8847b53dee625a133cfb02e88fd7bbf8]');//--></script></center>"
$('#inner_slide .module').replaceWith(htm);
but its remove the script. please help
First of all, you need to escape the double-quote in the string; for example:
var myStr = "hi this is an \"inner quote\".";
Secondly, break up the string as such:
myStr += "some html: <scr"+"ipt>my script</s"+"cript>";
document.write(myStr);
That should work.
jQuery messes with script tags when you pass HTML to it.
You can use http://api.jquery.com/jQuery.getScript/ to pull in the script or use the native javascript option http://www.hunlock.com/blogs/Howto_Dynamically_Insert_Javascript_And_CSS
InnerHTML is also an option. You can check out this question Can scripts be inserted with innerHTML?

Categories

Resources