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

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

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

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.

space in javascript

I have a little problem. I have a code with a form input, but the form input class is named
text-input small-input
I can't change this because of CSS issues and this is the problem, because when I add the space in my javascript code, my code doesn't work anymore
Javascript code
$(document).ready(function() {
$('.text-input*small-input').keyup(function() {
var search_term = $(this) .val();
$.post('search.php', {search_term:search_term}, function(data) {
$('.result').html(data);
$('.result li').click(function() {
var result_value = $(this).text();
$('.text-input*small-input') .val(result_value);
$('.result').html(' ');
});
});
});
});
So at the * sign, there needs to be a space. Any way to solve this? Thanks!
you do not want a space, you want nothing there. just .text-input.small-input to tell the selector engine to look for an element with both of those classes.
here is a very good article explaining multiple part selectors.
You had two issues. You don't want a space and you do want a dot on the second class.
To specify a requirement of two classes on the same object in a CSS selector, you put no space between the two class names:
$('.text-input.small-input') // find single object with both classes on it
With a space, it does something different:
$('.text-input .small-input') // find .small-input with ancestor .text-input
When you put a space between them, that creates a selector that finds an object that matches .text-input and a child that matches .small-input and the matched object is the child. No space between them means both classes must be on the same object. This is how CSS specifications work and isn't jQuery-specific.
FYI, what you were trying to do with this:
$('.text-input small-input') // find <small-input> with ancestor that is .text-input
was trying to find an object with a tag of <small-input> that had an ancesotr of .text-input because you put no special character in front of small-input so it was interpreted as a tag name.

How to add class to words starting with a hashtag in jQuery?

So let's say I have a string in jQuery that looks like
result.text = "I tweeted something #one #two #three";
Is there a way to wrap all the words starting with a hashtag with a span class called "tweet-hash" ?
You'll probably want to use some Regex to find the symbol/word combination, and replace it and wrap it with a style tag and a CSS class. CSS unfortunately doesn't have a selector for values like that.
$("#phrase").html($("#phrase").html().replace(/#([^ ]+)/, "<span class='hashtag'>$1</span>")
It's worth noting that the example above will only replace the first hashtag it finds. If you add a g global to the regex expression, it will target all instances that match the expression:
$("#phrase").html($("#phrase").html().replace(/#([^ ]+)/g, "<span class='hashtag'>$1</span>");
I've thrown up an example on jsFiddle so you can see the difference: http://jsfiddle.net/c26r9/

Categories

Resources