String replace (javascript) - javascript

I have a piece of string:
'Dow<br> <span class="table-sub-header">Value</span>'
I want to replace 'Value' inside the span with an arbitrary variable. I know that the span class will be there every time.
I've tried things like:
var s = 'Dow<br> <span class="table-sub-header">Value</span>';
And then doing a replace with something like this as the regex:
/<span class="table-sub-header">*</span>/
But it looks messy. Is there a clean way of doing this?
Edit: 'Value' in this case is arbitrary. I don't know what it is and I wanted a general method to replace what is in the span.

If you are working in browser, you may try put s in some element innerHTML and replace it as it in dom do
var s = 'Dow<br> <span class="table-sub-header">Value</span>';
t = document.createElement('div');
t.innerHTML = s;
t.querySelector('.table-sub-header').textContent = 'Something Else';
t.innerHTML // 'Dow<br> <span class="table-sub-header">Something Else</span>'
BTW, your regexp should be something like /<span class="table-sub-header">(.*)<\/span>/

Have you tried the replace string method?
var s = 'Dow<br> <span class="table-sub-header">Value</span>';
s = s.replace("Value", "New Value");

Yes, you can use jQuery for this.
var s = 'Dow<br> <span class="table-sub-header">Value</span>';
var div_wrapper = '<div style="display:none;">'+s+'</div>';
$(document).ready(function(){
$('body').append(div_wrapper);
var new_value = 'newvalue'; // an arbitrary variable
$('.table-sub-header').text(new_value);
console.log($('.table-sub-header').text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
</body>
</html>

You can dynamically replace what is in the span tag by using JavaScript or any JavaScript library. For example using Javascript you can use a class selector to select the span and set the inner html to whatever value you want based on a condition or logic of some sort. You can also use Jquery .text()
refer to the links below
https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML
http://api.jquery.com/text/

Related

Grabbing text from a span tag

I have some code for Javascript using jQuery, and I've been wondering how to fix an element of it.
var dataGiven = +$("span.cost-in-usd:first-child").text();
However, the span tag is:
<span class="cost-in-usd" data-se="product-usd-value">42</span>
Is there a way of modifying my code in order for it to recognise data-se?
Yes, use data.
var datase = $('.cost-in-usd').data('se');
Some links;
http://api.jquery.com/jquery.data/
Here's a jsfiddle
The following will return the value of attribute
$('.cost-in-usd').attr('data-se');

Javascript to replace a string inside a tag

<nav class="woocommerce-breadcrumb">Home > Product</nav>
Using jQuery or Javascript how would I be able to rename the word 'Product' to some other value?
var brandname = $('.tax-product_brand h1.page-title').text();
var crumb = $('.woocommerce-breadcrumb').text();
console.log(crumb);
crumb.replace("Product", brandname);
I tried the above with no luck
Use .html() rather than .text() or else you'll lose your markup:
var crumb = $('.woocommerce-breadcrumb').html();
Then apply the value back to the element:
$('.woocommerce-breadcrumb').html(crumb.replace("Product", brandname));
Alternatively, a much easier way would be to put "Product" in its own element, and then just replace that element's text:
<nav class="woocommerce-breadcrumb">Home > <span class="item">Product</span></nav>
Then your jQuery would simply be:
$(".woocommerce-breadcrumb .item").text(brandname);
You then need to insert your string into the DOM. As it is, you're just doing a string operation and discarding the return value.
$('.woocommerce-breadcrumb').text(crumb.replace("Product", brandname));
EDIT: As mentioned in a comment, you should use .html() instead of .text(). .text() will strip all of your HTML, i.e. your <a> tag.
.replace returns a new string, so you have to set the text of crumb with the returned string.
Its replaced Here is demo.
var brandname = 'My Name';
var crumb = 'My Product';
console.log(crumb);
var d= crumb.replace("Product", brandname);
alert(d);
var brandname = $('.tax-product_brand h1.page-title').text();
$(".woocommerce-breadcrumb:contains('Product')").html(function(_, html) {
return html.replace(/(Product)/g, '<span>'+brandname+'</span>')
});
I was able to use the above to gain what I wanted whilst keeping the formatting of the a tag
Avoid using free text. This will increase processing overhead, when you'll do DOM calculations.
It is good, if you can use tag to display the end product/page name.
The html will look like:
<nav class="woocommerce-breadcrumb">
<a href="http://domain.com/" class="home">
Home
</a>
<span class="currentPage">>Product</span>
</nav>
Now, you can use simple DOM operation to change the text() of expected element.
var currentPage=$(".currentPage");
$(currentPage).text('> NewText');

How do I remove an element but not its content with javascript?

I have a string which is a simple <a> element.
var str = 'Link'
Which I want to turn into:
Link
I can remove the </a> part easily with str.replace("</a>", "")but how would I remove the opening tag <a href="somewhere.com>?
Use unwrap like
$('a').contents().unwrap();
But it work with the elements that are related to DOM.For your Better solution try like
str = ($(str).text());
See this FIDDLE
This will strip the whole tag:
str.replace(/<[^>]+>/g,'');
And this just the first part:
str.replace(/<[^/>]+>/g, '');
Since you are using jQuery, you can do it on the fly as follows
$('Link').text()
Can you try this,
var str = 'Link';
alert($(str).text());

Get an attributes value of the ALT attribute of a hyperlink

My a-tag (link) contains innerHTML which is an image like this:
.innerHTML = <img alt="hello world" src="/Content/Images/test.png">
How can I get the text of the alt attribute with JQuery?
You really don't need jQuery. If you have the a element you can do this:
// lets call the anchor tag `link`
var alt = link.getElementsByTagName('img')[0].alt; // assuming a single image tag
Remember attributes map to properties (most), and unless the property is changed, or the attribute, the two should reflect the same data (there are edge cases to this, but they can be handled case-by-case).
If you truly do need the attribute there is
var alt = link.getElementsByTagName('img')[0].getAttribute('alt');
Last scenario is if you only have the image tag as a string.
var str = '<img alt="hello world" src="/Content/Images/test.png">';
var tmp = document.createElement('div');
tmp.innerHTML = str;
var alt = tmp.getElementsByTagName('img')[0].alt;
If you must use jQuery (or just prefer it) then the other answer provided by Alexander and Ashivard will work.
Note: My answer was provided for completeness and more options. I realize the OP asked for jQuery solution and not native js.
Being $a your <a/> element.
Using jQuery you can do:
$("img", $a).first().attr("alt");
Or, using pure JavaScript:
var $img = $a.getElementsByTagName("img")[0];
console.log($img.alt);
​
See it here.
use this.
var altName=$('a img').attr('alt');

insert/remove HTML content between div tags

how can I insert some HTML code between <div id="mydiv">...</div> using javascript?
Ex: <div id="mydiv"><span class="prego">Something</span></div> its about 10 lines of html of most. thank you
If you're replacing the contents of the div and have the HTML as a string you can use the following:
document.getElementById('mydiv').innerHTML = '<span class="prego">Something</span>';
A simple way to do this with vanilla JavaScript would be to use appendChild.
var mydiv = document.getElementById("mydiv");
var mycontent = document.createElement("p");
mycontent.appendChild(document.createTextNode("This is a paragraph"));
mydiv.appendChild(mycontent);
Or you can use innerHTML as others have mentioned.
Or if you would like to use jQuery, the above example could be written as:
$("#mydiv").append("<p>This is a paragraph</p>");
// Build it using this variable
var content = "<span class='prego'>....content....</span>";
// Insert using this:
document.getElementById('mydiv').innerHTML = content;
That's really kind of an ambiguous request. There are many ways this can be accomplished.
document.getElementById('mydiv').innerHTML = '<span class="prego">Something</span>';
That is the simplest. OR;
var spn = document.createElement('span');
spn.innerHTML = 'Something';
spn.className = 'prego';
document.getElementById('mydiv').appendChild(spn);
Preferred to both of these methods would be to use a Javascript library that creates shortcut methods for the simple things like this, such as mootools. (http://mootools.net)
With mootools this task would look like:
new Element('span', {'html': 'Something','class':'prego'}).inject($('mydiv'));
document.getElementById("mydiv").innerHTML = "<span class='prego'>Something</span>";
Should do it. If you are willing to use jQuery it could be easier.
document.getElementById('mydiv').innerHTML = 'whatever';
Javascript
document.getElementById('mydiv').innerHTML = '<span class="prego">Something</span>';
jQuery
$("#mydiv").append('<span class="prego">Something</span>');

Categories

Resources