Jquery contains to remove certain character - javascript

<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

Related

replace all specific character inside div with jquery

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');

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())

JQuery: Cut off div text after 4 characters

I only want to display the first four characters of a div, but it seems to be more difficult than needed and google isn't very helpful. Different variations of this don't seem to work:
$("#div").html(this.html().substring(0,4));
I really want to avoid having an extra variable in there that stores the text first.
Use a callback for the .html(),
$('#div').html(function(i, currentHtml) {
return currentHtml.substring(0, 4);
});
Demo
You can also use .text() in this case if the div consists only of plain text.
$("#div").text(function(i, currentText) {
return currentText.substring(0, 4);
});
Refer :
Slice vs Substring
Turns out substring is relatively faster.
JsPerf test : slice() vs substring() vs others
If the div elements contains any HTML (html elements) then .html() return the it's as a string. Example
Note: (It's completely depend on the inner content of you div)
If you want to truncate the plain text, you should use .text() instead of using .html()
Try this:
$("#div").text(function(){
return $(this).text().substring(0,4);
});
Working Fiddle
Try this :
$("#div").html(function(){
return $(this).html().substring(0,4)
});
It will count space also...If any there.
Like DIV have "test four 3" will give you output "test"
Use slice() for this purpose :
$("#div").text(function(){
return $(this).text().slice(0,4);
});

jquery function works after single space in quotes

I am learning jQuery and new to it. I was trying to run some code but it was not running and then I found that I just need to give one space before ending double commas/quotes "
$("div:not([id=header]) " + strWhichTag).each(function(){
//some function
});
Now the question is that why do we need to give space after id=header]) if I remove that space and use this code, it doesn't work, the code below doesn't work but Why
$("div:not([id=header])" + strWhichTag).each(function(){
//some function
});
CHANGES------------------------
strWhichTag is basically h3 but it is not child to #header
Second thing I need to know is this
var oList = $("<ul id='bookmarksList'>");
here can I use single quotes and double quotes alternatively or I need to keep the same level like using double quotes and use sigle quotes inside them
I am learning it so any help will be appriciated
First question
The jQuery's argument is a CSS selector.
The space means that you are selecting a child of div:not([id=header]);
"div:not([id=header]) div#foo"
is not the same as
"div:not([id=header])div#foo"
Second question:
The "hierarchy" of quotes doesn't matter, "text'foo'dd" is OK, just as 'text"foo"dd'.
It's up to your taste, but usually using single quotes outside is more practical, since you can have the double ones, used most of the time, in the string.
Lets say
var strWhichTag = 'span';
$("div:not([id=header])" + strWhichTag)
evaluates to $("div:not([id=header])span") // No tag where div and span are equivalent
But if the same is $("div:not([id=header]) span") .. It will try to find all the spans inside the div tag which does not have given id
I dont know what strWhichTag but let assume it is a string like .class
without space, you arent looking a div that is not #header and with the class class.
<div class='class'></div>
This would be ok.
With a space, you are looking for an element with class class inside a div not #header.
<div><img class='class' /></div>
Here, it would select the img.

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?'.

Categories

Resources