I have the following code:
$('.breadcrumb:contains(",")').hide();
It does as expected and hides the entire breadcrumb,
but how would I go about just remove the comma?
==========
EDIT:
<div class="breadcrumb">
Link 1,
Link 2
</div>
==========
Thanks for any help
You can do it like this:
$('.breadcrumb:contains(",")').html(function(i, h) {
return h.replace(/,/g, '');
});
The .html() function accepts a function, you can see the docs here. The above code replaces all commas in all .breadcrumb elements. Example here: http://jsfiddle.net/ZZG8p/
$('.breadcrumb:contains(",")').html($('.breadcrumb:contains(",")')
.html().replaceAll(",", ""));
.hide() hides the selected node. You're going to have to get the text from the node (using .text()), parse it to pull out the comma, and then re-set the text on the node.
You can JavaScript's String replace method. However, I'm going to go out on a limb and imagine what happened. You had and an array and then you looped through it to generate your bread crumbs and now you want to get rid of the trailing comma.
The solution to that problem is to use split() and use ',' as the separator. This way you only have internal commas.
$('.breadcrumb:contains(",")').remove();
Though this will remove it from the DOM, so make sure you select the correct one.
Related
This is a problem I'm running into and I'm not quite sure how to approach it.
Say I have a paragraph:
"This is a test paragraph. I love cats. Please apply here"
And I want a user to be able to click any one of the words in a sentence, and then return the entire sentence that contains it.
You first would have to split your paragraph into elements, as you can't (easily) detect clicks on text without elements :
$('p').each(function() {
$(this).html($(this).text().split(/([\.\?!])(?= )/).map(
function(v){return '<span class=sentence>'+v+'</span>'}
));
});
Note that it splits correctly paragraphs like this one :
<p>I love cats! Dogs are fine too... Here's a number : 3.4. Please apply here</p>
Then you would bind the click :
$('.sentence').click(function(){
alert($(this).text());
});
Demonstration
I don't know if in English : is a separator between sentences. If so, it can be added to the regex of course.
First of all, be prepared to accept a certain level of inaccuracy. This may seem simple on the surface, but trying to parse natural languages is an exercise in madness. Let us assume, then, that all sentences are punctuated by ., ?, or !. We can forget about interrobangs and so forth for the moment. Let's also ignore quoted punctuation like "!", which doesn't end the sentence.
Also, let's try to grab quotation marks after the punctuation, so that "Foo?" ends up as "Foo?" and not "Foo?.
Finally, for simplicity, let's assume that there are no nested tags inside the paragraph. This is not really a safe assumption, but it will simplify the code, and dealing with nested tags is a separate issue.
$('p').each(function() {
var sentences = $(this)
.text()
.replace(/([^.!?]*[^.!?\s][.!?]['"]?)(\s|$)/g,
'<span class="sentence">$1</span>$2');
$(this).html(sentences);
});
$('.sentence').on('click', function() {
console.log($(this).text());
});
It's not perfect (for example, quoted punctuation will break it), but it will work 99% of the time.
Live demo: http://jsfiddle.net/SmhV3/
Slightly amped-up version that can handle quoted punctuation: http://jsfiddle.net/pk5XM/1/
Match the sentences. You can use a regex along the lines of /[^!.?]+[!.?]/g for this.
Replace each sentence with a wrapping span that has a click event to alert the entire span.
I suggest you take a look at Selection and ranges in JavaScript.
There is not method parse, which can get you the current selected setence, so you have to code that on your own...
A Javascript library for getting the Selection Rang cross browser based is Rangy.
Not sure how to get the complete sentense. but you can try this to get word by word if you split each word by spaces.
<div id="myDiv" onmouseover="splitToSpans(this)" onclick="alert(event.target.innerHTML)">This is a test paragraph. I love cats. Please apply here</div>
function splitToSpans(element){
if($(element).children().length)
return;
var arr = new Array();
$($(element).text().split(' ')).each(function(){
arr.push($('<span>'+this+' </span>'));
});
$(element).text('');
$(arr).each(function(){$(element).append(this);});
}
I have a Textarea which is in a form that has this value
Hello<div class="author"><br /><i> Written By admin </i></div>
I need to remove everything in the author class on load cause i will be adding the same updated data on submit.
You can simply replace that piece with regex:
textarea.val(textarea.val().replace(/<div class="author">.*?<\/div>/, ''));
Demo: http://jsfiddle.net/TimWolla/Nzvy7/
Probably not the answer you are looking for, but how exactly do you add text to the textarea on submit, and why don't just use the same method for removing text.
On the other hand doing:
$('#textareaID').val('Hello');
Will give you exactly the same result as removing the rest of the text and just keeping 'Hello'.
It's not exactly clear from the question, but to remove the <div class="author"> and its contents you can use split and shift:
$("textarea").val().split("<div class=\"author\"").shift();
http://jsfiddle.net/xtnL7/1/
I am trying to remove BBCode with attributes and content between those tags. I'm using this regular expression that I got here from here. I also tried other regex I found on stackoverflow but they didn't work for me, just the one I copy here is the closest.
([[\/\!]*?[^\[\]]*?])
I added a . before *?]) and it maches the text between the tags but also matches pokemon and I don't want that.
**Regex**: ([[\/\!]*?[^\[\]].*?])
**Text**: I'm a pokemon master and I like
[TAG] this [/TAG] pokemon [TAG] and this [/TAG] text...
I use this web to test regex http://regexpal.com/
Can anyone help me?
Thanks in advance.
str = str.replace(/\[(\w+)[^\]]*](.*?)\[\/\1]/g, '');
jsFiddle.
This is what you want:
.replace(/\[(\w+)[^\]]*](.*?)\[\/\1]/g, '$2');
JavaScript demo
Basically you catch the value between tags and then replace the whole string with that value.
Using a regex to do this isn't a very clean way of doing it though...
Sorry Alex but you didn;t read it seems.
This should do:
\[(\w+).*?\].*?\[/\1\]
This will look for a closing tag matching the opening tag - and also accept attributes on the opening tag. The JavaScript code should then be:
str = str.replace(/\[(\w+).*?\].*?\[\/\1\]/, "");
I'm trying to get the first letter in a paragraph and wrap it with a <span> tag. Notice I said letter and not character, as I'm dealing with messy markup that often has blank spaces.
Existing markup (which I can't edit):
<p> Actual text starts after a few blank spaces.</p>
Desired result:
<p> <span class="big-cap">A</span>ctual text starts after a few blank spaces.</p>
How do I ignore anything but /[a-zA-Z]/ ? Any help would be greatly appreciated.
$('p').html(function (i, html)
{
return html.replace(/^[^a-zA-Z]*([a-zA-Z])/g, '<span class="big-cap">$1</span>');
});
Demo: http://jsfiddle.net/mattball/t3DNY/
I would vote against using JS for this task. It'll make your page slower and also it's a bad practice to use JS for presentation purposes.
Instead I can suggest using :first-letter pseudo-class to assign additional styles to the first letter in paragraph. Here is the demo: http://jsfiddle.net/e4XY2/. It should work in all modern browsers except IE7.
Matt Ball's solution is good but if you paragraph has and image or markup or quotes the regex will not just fail but break the html
for instance
<p><strong>Important</strong></p>
or
<p>"Important"</p>
You can avoid breaking the html in these cases by adding "'< to the exuded initial characters. Though in this case there will be no span wrapped on the first character.
return html.replace(/^[^a-zA-Z'"<]*([a-zA-Z])/g, '<span class="big-cap">$1</span>');
I think Optimally you may wish to wrap the first character after a ' or "
I would however consider it best to not wrap the character if it was already in markup, but that probably requires a second replace trial.
I do not seem to have permission to reply to an answer so forgive me for doing it like this. The answer given by Matt Ball will not work if the P contains another element as first child. Go to the fiddle and add a IMG (very common) as first child of the P and the I from Img will turn into a drop cap.
If you use the x parameter (not sure if it's supported in jQuery), you can have the script ignore whitespace in the pattern. Then use something like this:
/^([a-zA-Z]).*$/
You know what format your first character should be, and it should grab only that character into a group. If you could have other characters other than whitespace before your first letter, maybe something like this:
/.*?([a-zA-Z]).*/
Conditionally catch other characters first, and then capture the first letter into a group, which you could then wrap around a span tag.
Using a ajax request I want to change content of my div.
<div id="d1">202</div>
So I want to change the content to a different number.
$('d1').InnerText???
Also, say I wanted to increment the number, how could I do that? Do I have to convert to int?
$("#di").html('My New Text');
Check out the jQuery documentation.
If you wanted to increment the number, you would do
var theint = parseInt($("#di").html(),10)
theint++;
$("#di").html(theint);
P.S. Not sure if it was a typo or not, but you need to include the # in your selector to let jQuery know you are looking for an element with an ID of di. Maybe if you come from prototype you do not expect this, just letting you know.
This would changed the inner text of your HTML element.
$('#d1').text(parseInt(requestResponse)++);
Unless you're embedding html like <b>blah</b> I'd suggest using $("#di").text() as it'll automatically escape things like <, > and &, whereas .html() will not.
Use the text function:
$("#d1").text($("#d1").text() + 1);
$('#d1').html("Html here");
jQuery('#d1').html("Hello World");
if your value is a pure text (like 'test') you could use the text() method as well. like this:
$('#d1').text('test'); Or $('#d1').html('test');
anyway, about the problem you are sharing, I think you might be calling the JavaScript code before the HTML code for the DIV is being sent to the browser. make sure you are calling the jQuery line in a <script> tag after the <div>, or in a statement like this:
$(document).ready(
function() {
$('#d1').text('test');
}
);
this way the script executes after the HTML of the div is parsed by the browser.
$("#div1").innerHTML="your text goes here..";