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.
-
Are you within a browser environment? Can you interact with the DOM to get hold of this?James Thorpe– James Thorpe2016年06月15日 15:44:17 +00:00Commented Jun 15, 2016 at 15:44
-
I am on the browser and I'm getting this value as a property from a library object. I thought it would be weird to change it to a DOM object just for a string placement, especially since I would need to convert the DOM object back to a string.user1413969– user14139692016年06月15日 15:47:31 +00:00Commented Jun 15, 2016 at 15:47
4 Answers 4
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>/
Comments
Have you tried the replace string method?
var s = 'Dow<br> <span class="table-sub-header">Value</span>';
s = s.replace("Value", "New Value");
3 Comments
var s = 'Dow<br> <span class="table-sub-header">New Value</span>'; in the first place.$(".table-sub-header").text("my text")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/