replace all specific character inside div with jquery - javascript

I'm trying to replace all the commas (",") inside the div with a character. I've tried googling and it seems .replace() replaces only the first comma and it removes the links from the text1.
How do I replace all the commas with another character inside the div without it removing the links, using jquery?
<div>
text1, text2, text3, text4,
</div>

Get all text node inside the div and update it, that will be the better way than updating entire html inside div.
$('div')
.contents() // get all child nodes
.each(function() { // iterate over them
if (this.nodeType == 3) // check node type is text
this.textContent = this.textContent.replace(/,/g, '+'); // update text content if it's text node
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
text1, text2, text3,
</div>

It will replace all , with 'a' character. use of the "g" within this - that stands for "global" and causes the replacing of all of the target characters in the string - without it you just replace the first instance as you have discovered. try it.
string.replace(/\,/g, 'a');

Related

Jquery contains to remove certain character

<p>some string here xxx</p>
I want to remove the xxx characters
so I do $(p:contains('xxx')).remove(); but it removed the entire <p></p>, how to only get rid of the targeted character?
That would be the text method and a string replace
$('p').text(function(_, txt) {
return txt.replace('xxx', '');
});
remove removes entire elements, not parts of text.
That is the expected behavior of remove(), it removes whole elements . You can use text(fn) or html(fn) to do it.
$("p:contains('xxx')").text(function(idx, oldText){
return oldText.replace('xxx','');
});
If you also have other tags within the p use html(fn) as above

How to remove variable number of p tags from a string in jQuery

I have a string that contains variable HTML content. The string can contain one, more or no p tags which may also have classes on them.
What is the best way to remove all p tags from this using jQuery while keeping the HTML content of each of them.
I first tried the following but of course this only works if I have the whole string wrapped in a paragraph and it would not cover if the paragraphs have classes or other attributes on them:
str.substring(3).slice(0, -4);
Edit
Here is an example but the number of p tags can vary and there can also be none at all.
Example before:
<p>Some text <p class="someClass"> Some other text</p> Some more text</p>
Example after:
"Some text Some other text Some more text"
Use Unwrap: $('p').contents().unwrap()
It is the opposite of wrap in that it removes the parents of the selector. The p tags are the parent elements of the content, selecting the content before unwraping will unwrap the p tags. jsFiddle
You could use a regular expression to do this. It only removes the p-tags and leaves all other tags in place.
JavaScript
var string = "<p>this is a test with <p class='bold'>multiple</p> p-tags.</p><span>THIS IS COOL</span>";
var result = string.replace(/<[\/]{0,1}(p)[^><]*>/ig,"");
console.log(result);
FIDDLE
If you'd like to remove all tags, you could use /(<([^>]+)>)/ig instead as regex.
Try the following:
var str = "<p>Test</p>";
var res = str.replace("<p>", "").replace("</p>", "");
If I understand correctly, and you want the p tags removed but the content still there it should be as simple as:
str.replace('<p>', '').replace('</p>', '');
You can also use replaceWith - jsFiddle Example, readable and works with parent / child tags
$('p').replaceWith($('p').text())

How to hide HTML element containing only spaces using jQuery?

I have the following HTML :
<div id="rightCon">
</div>
And then I have the following script at the top :
$('#rightCon:empty').hide();
Why is the div not hiding? I can see that there is some spaces(that I canĀ“t get ridoff) but does that really matter? How do I remove/hide this div when its empty with only spaces?
Your element appears to have a bunch of white space, which will give it a text node. It won't be matched by :empty for that reason.
You could try finding the element and checking it's contents explicitly:
$('#rightCon').filter(function() {
var text = $(this).text().replace(/\s*/g, '');
return !text;
}).hide();
This solved the problem.
$(document).ready(function () {
if($('#rightCon').text().trim().length < 1)
{$('#rightCon').hide();}
});
Your div is not actually empty (It contains whitespace). So the selector $("#rightCon:empty") will never evaluate and hide the div.
Since HTML elements should be unique, you can safely assume that you can select the correct element via:
var rightCon = $("#rightCon");
You can then hide the element via:
right.hide();
Or
$("#rightCon").hide();

In JQuery, how do I remove a comma after removing an element?

var body = 'Alex, Jason, Kate, how are you?";
I want to use JQuery to remove the anchor element from body, and then also remove the comma after the anchor, if there is any. Note: to make it easy, the comma will always be after the anchor with no other characters in between.
I'm assuming (to maintain grammatical consistency) that you also want to remove the contents of the anchor.
Firstly, use a regexp to get rid of the comma:
var body = 'Alex, Jason, Kate, how are you?';
body = body.replace(/(<\/a>),/g, '$1')
Then to allow jQuery to work on the string you need to enclose it in an element:
body = '<div>' + body + '</div>'
Then you can actually remove the element
body = $(body).children('a').remove().end().html();
NB: the code above will remove all <a> elements within the text, but leave other HTML elements therein untouched.
If you're thinking of removing elements like that then it would be better to encase them in something to "mark them off" as it were. You're saying that the name "Jason" is tied to the superseding comma, so mark them off. e.g.:
var body = 'Alex, <span class="name">Jason,</span> Kate, how are you?";
Then to remove in jquery you can do something like:
$('a').click(function(){ $(this).closest('.name').remove(); });
This is the best way to do it, mainly because you have control over what is important to which text elements. A regex, or some way of removing the next single character will work in your example, however what happens if you want to extend your sentence, eg: 'Alex, Jason (the farmer's son), Kate, how are you?'.

jQuery replace text leaving siblings intact

I'm having trouble wrapping my head around what should be a simple solution. I want to replace text within a label tag, without affecting the other 'siblings', if they exist.
Sample markup:
<fieldset class="myFieldsetClass">
<legend>Sample Fieldset</legend>
<ol>
<li>
<label>
<span class="marker">*</span>
Some Label 1
</label>
</li>
<li>
<label>
Some Label 2
</label>
</li>
<li>
<label>
Text that doesn't match...
</label>
</li>
</ol>
</fieldset>
Goal:
To replace text Some Label X with Some Label (I.e. remove X from the label text).
span tags within label must stay intact if they exist, such as the <span class="marker"> above.
I do not know the value of X, which could be 1 or more characters long.
Current Script:
My jQuery script below works, but I know is very inefficient. I can't seem to wrap my head around this one for some reason...
//for each label in the fieldset that contains text "Some Label "
$(".myFieldsetClass label:contains('Some Label ')").each(function() {
if ($(this).has("span").length > 0) {
//if the label has the span tag within, remove it and prepend it back to the replaced text
$(this).find("span").remove().prependTo($(this).text(labelText));
}
else {
//otherwise just replace the text
$(this).text('Some Label');
}
});
I thought at first I could simply do:
$(".myFieldsetClass label:contains('Some Label ')").text("Some Label");
But this clears all contents of the label and hence removes the span, which I don't want. I can't use any replace functions to replace Some Label X with Some Label because I don't know what X will be.
Can anyone suggest a more elegant/efficient approach to this problem?
Thanks.
EDIT
After trying multiple answers, I think the problem seems to be that even if I select the right collection, they are text nodes, which jquery doesn't seem to want to modify.. I've used FireBug to select the collection (many answers below all select correctly but in slightly different ways). In firebug console resulting set is:
[<TextNode textContent="Some Label 1:">,
<TextNode textContent="Some Label 2:">,
<TextNode textContent="Some Label 3:">,
<TextNode textContent="Some Label 4:">,
<TextNode textContent="Some Label 5:">]
The problem seems to be that calling .replaceWith(), .replace(), .text(), etc. doesn't seem to affect the jquery collection. If I allow the above collection to contain one of the spans, then calling .replaceWith(), .replace(), etc functions correctly against the span, but the text nodes stay as is..
Try:
$(".myFieldsetClass label:contains('Some Label ')").contents().filter(':last-child').text("Some Label");
This should work assuming the text to be replaced will always be at the end. The contents() function selects all nodes, including text nodes.
http://api.jquery.com/contents/
EDIT: I should have used filter() instead of find(). Corrected.
EDIT: Works now. Here's one way.
// Store proper labels in a variable for quick and accurate reference
var $labelCollection = $(".myFieldsetClass label:contains('Some Label ')");
// Call contents(), grab the last one and remove() it
$labelCollection.each(function() {
$(this).contents().last().remove()
});
// Then simply append() to the label whatever text you wanted.
$labelCollection.append('some text')
As patrick points out, you can use contents() to select the text alone, and then do a replace on it all. Adapting the example given there, you could also try:
$(".myFieldsetClass label:contains('Some Label ')").contents().filter(function() {
return this.nodeType == 3 && $(this).is(":contains('Some Label ')");
})
.replaceWith("Some Label");
However, if you know that "Some Label " will always be the last element in the <label> then patrick's method will be faster I believe.
Why not simply do an entire replace using regex?
$(".myFieldsetClass label:contains('Some Label ')")
.each(function() {
$(this).html($(this).html().replace(/Some Label ./, "Some Label"));
});
A one-liner:
$('.myFieldsetClass label').contents().last().remove().end().first().after('New Label')

Categories

Resources