JQuery: replace a string inside a div - javascript

<div id="content">
...
<p>NUMBER times...</p>
...
<p>Place N°: NUMBER</p>
</div>
How do I replace all NUMBER inside the content div?
I tried replace method but it didn't work.
Thanks.

You can use the standard Javascript replace function for strings.
oldhtml = $('div#content').html();
var newhtml = oldhtml.replace(/NUMBER/g, "123");
$('div.demo-container').html(newhtml);

You should iterate all your text nodes and replace the text inside them.
$('#content').children().each(function() {
var textNode = $(this);
textNode.text(textNode.text().replace("NUMBER", "NEW"));
});
This codes assumes all the children of #content just contain text.

Try this:
$('#content').children().each(function () {
$(this).html(function (i, html) {
return $(this).html().replace(/NUMBER/g, '123456');
});
});

Related

Create H1 element in div jQuery

I want to a <h1></h1> element in a div element in HTML with jQuery. How do I do this?
function show() {
let text = "greetings"
let divElem = document.getElementById("hello");
divElem.innerHTML = '<h1>${text}</h1>'
}
<div id="hello"></div>
<button onclick="show()">show</button>
Basically, I want to make an h1 element in the div element which displays the string contained in the text variable, "greetings" how do I do this?
Do you need to ` instead of ' ?!
Also can read about it in this link : Template literals (Template strings).
function show() {
let text = "greetings"
let divElem = document.getElementById("hello");
divElem.innerHTML = `<h1>${text}</h1>`
}
<div id="hello"></div>
<button onclick="show()">show</button>
You can use the Jquery .html() method.
Also, you have to use backticks instead of quotes. (`) in order to use templating inside a "string". This is called Template literals. You can read more about them here
function show() {
let text = "greetings"
$( "#hello" ).html( `<h1>${text}</h1>` );
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="hello"></div>
<button onclick="show()">show</button>

How to add hyperlink in jquery replace

I have the following script and I want to replace barbel with a href
$(".text_div, p").text(function() {
return $(this).text().replace("barbel", 'mpara');
});
$(".text_div").text(function() {
return $(this).text().replace("some", "red");
});
You have a few issues here:
Use html(), not text(), to insert HTML in to the DOM.
Be careful with your quotes as you're causing a syntax error by mis-matching them.
Use the second argument of the handler function to receive the current HTML value of the element instead of creating another jQuery object by accessing the DOM again.
With all that said, try this:
$(".text_div, p").html(function(i, html) {
return html.replace('barbel', 'mpara');
});
Try this:
console.log('Before:');
console.log($('.content').html());
$(".text_div ,p").each((index, elem) => {
let newHtml = $(elem).html().replace('barbel', 'mpara');
$(elem).html(newHtml);
});
$(".text_div").each((index, elem) => {
let newHtml = $(elem).html().replace('some', "red");
$(elem).html(newHtml);
});
console.log('\n\nAfter:');
console.log($('.content').html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<div class="content">
<div class="text_div">This is barbel</div>
<p class="tag_p">That is barbel again</p>
<div class="text_div">Some some</div>
</div>

How to get Html Element's Text

I want to extract the text part of the html.
If I have <p>ABCD</p>
I want the out put to be ABCD
Something like,
var html='<p>ABCD</p>';
var str = convertToString(html);
Hope, I will need a function which converts from html to string, or maybe extract string from it.
You can use jQuery to extract the text content from the string
var html = '<p>ABCD</p>';
var str = $(html).text();//get a jQuery reference and then read its text content
console.log(str)
All you need is a selector(id,class name etc) of get the required element of DOM and use .text() to get text part of the html.
HTML
<p>ABCD</p>
Jquery
var str = $('p').text(); // $('p') "p" is a selector to select p element(s)
console.log(str)
DEMO
JavaScript way
var txt = document.getElementById("demo").innerHTML;
alert(txt);
<p id="demo">Test text</p>
var html = '<p>ABCD</p>';
var str = $(html).text();
console.log(str);
This would do the task.

Prevent html tag creation during html() using Jquery

I am having a string "<F1>" and whenever I add it as html to a particular div using jquery's html(), as
var str = "<F1>";
$("div").html(str);
It generates html for div as
"<f1></f1>"
But I dont want such tag creation.
I need to have div with html as
"<F1>"
It will be appreciated if somebody guide me, to achieve this. :(
Use .text() instead of .html().
var str = "<F1>";
$("div").text(str);
Fiddle: http://jsfiddle.net/6942a/
To escape the HTML entities in str and use .html() you can do the following:
var str = "<F1>";
str = $("<div/>").text(str).html();
$("div").html(str);
Updated jsfiddle: http://jsfiddle.net/6942a/3/
Use this :
HTML:
<div></div>
<input type="text">
<input type="button" value="ADD">
jQuery :
$(function(){
$('input[type=button]').click(function(){
var text = $('input[type=text]').val();
text =text.replace('<','&#60');
text =text.replace('>','&#62');
$("div").html(text);
});
});
Demo
For more information see html entities
Try this
var str = '<f1>';
var res = str.replace("<", "<");
res=res.replace(">", ">");
$("div").text(res);
Fiddle

jQuery find and replace string

I have somewhere on website a specific text, let's say "lollypops", and I want to replace all the occurrences of this string with "marshmellows". The problem is that I don't know where exactly the text is. I know I could do something like:
$(body).html($(body).html().replace('lollypops', 'marshmellows'));
This would probably work, but I need to rewrite as little HTML as I can, so I'm thinking something like:
search for the string
find the closest parent element
rewrite only the closest parent element
replace this even in attributes, but not all, for example replace it in class, but not in src
In example, I would have structure like this
<body>
<div>
<div>
<p>
<h1>
<a>lollypops</a>
</h1>
</p>
<span>lollypops</span>
</div>
</div>
<p>
<span class="lollypops">Hello, World!</span>
<img src="/lollypops.jpg" alt="Cool image" />
</p>
<body>
In this example, every occurrence of "lollypops" would be replaced, only <img src="... would remain the same and the only elements that would actually be manipulated would be <a> and both <span>s.
Does anybody know how to do this?
You could do something like this:
$("span, p").each(function() {
var text = $(this).text();
text = text.replace("lollypops", "marshmellows");
$(this).text(text);
});
It will be better to mark all tags with text that needs to be examined with a suitable class name.
Also, this may have performance issues. jQuery or javascript in general aren't really suitable for this kind of operations. You are better off doing it server side.
You could do something this way:
$(document.body).find('*').each(function() {
if($(this).hasClass('lollypops')){ //class replacing..many ways to do this :)
$(this).removeClass('lollypops');
$(this).addClass('marshmellows');
}
var tmp = $(this).children().remove(); //removing and saving children to a tmp obj
var text = $(this).text(); //getting just current node text
text = text.replace(/lollypops/g, "marshmellows"); //replacing every lollypops occurence with marshmellows
$(this).text(text); //setting text
$(this).append(tmp); //re-append 'foundlings'
});
example: http://jsfiddle.net/steweb/MhQZD/
You could do something like this:
HTML
<div class="element">
<span>Hi, I am Murtaza</span>
</div>
jQuery
$(".element span").text(function(index, text) {
return text.replace('am', 'am not');
});
Below is the code I used to replace some text, with colored text. It's simple, took the text and replace it within an HTML tag. It works for each words in that class tags.
$('.hightlight').each(function(){
//highlight_words('going', this);
var high = 'going';
high = high.replace(/\W/g, '');
var str = high.split(" ");
var text = $(this).text();
text = text.replace(str, "<span style='color: blue'>"+str+"</span>");
$(this).html(text);
});
var string ='my string'
var new_string = string.replace('string','new string');
alert(string);
alert(new_string);
Why you just don't add a class to the string container and then replace the inner text ? Just like in this example.
HTML:
<div>
<div>
<p>
<h1>
<a class="swapText">lollipops</a>
</h1>
</p>
<span class="swapText">lollipops</span>
</div>
</div>
<p>
<span class="lollipops">Hello, World!</span>
<img src="/lollipops.jpg" alt="Cool image" />
</p>
jQuery:
$(document).ready(function() {
$('.swapText').text("marshmallows");
});

Categories

Resources