jQuery or JS to trim characters from inside a span - javascript

I'm trying to remove the end of some text within a span using jQuery or JS.
<h3 class="ms-standardheader ms-WPTitle">
<a href="" tabindex="0" accesskey="W">
<nobr>
<span>Programs ‭[1]‬</span>
I have 15 titles that are generated like this in SharePoint - 5 Programs, 5 Clinical Services, and 5 Other Support. I want to remove the [x] from each of them, however this is auto generated by SharePoint because it doesn't like having titles of the same name.
I've tried iterations of:
$('.ms-WPTitle a nobr span').splice(0, -4);
I can't seem to get at the text within the span to trim it. Any suggestions?

$('.ms-WPTitle a nobr span').text(function(el, old){
return old.slice(0, -4);
});
.text() accepts a function, which you can use to easily trim chars
Demo: http://jsfiddle.net/vhTuA/

Since ahren has given one approach you can try this as well: you can also try
demo http://jsfiddle.net/CCvPQ/2/ or http://jsfiddle.net/CCvPQ/4/
API used:
http://api.jquery.com/first/
http://api.jquery.com/text/
http://api.jquery.com/find/
Hope it fits the cause :)
code
jQuery.fn.justtext = function() {
return $(this).children().find('span').text();
};
alert($('.ms-standardheader').justtext());
using .first api
http://jsfiddle.net/qRZe7/1/
jQuery.fn.justtext = function() {
return $(this).children().find('span').first().text();
};
alert($('.ms-standardheader').justtext());

Related

Regex in javascript replace function

Am newbie to regex am trying to do some regex replace function in java script here is my content and code
jQuery("td[headers='name_head']").each(function (index, value) {
var text = jQuery(this).html();
if( text.indexOf('<a href=') >= 0){
jQuery(this).text(text.replace(/<a href=.*\"$/, ""));
}
});
Html content will be look like this
Calculate Points
i just want to remove only the value inside href ""
Please throw some light on this
Regards
Sathish
The text() method just retrieves the text contents which doesn't include any HTML tags. You can use html() method with a callback function where you can get the old HTML content as the second argument to the callback and based on the old value generate updated HTML.
The better way is to update the href attribute value of a tag to empty by directly selecting them, there is no need to loop over them since all values need to be empty.
jQuery("td[headers='name_head'] a").attr('href', '');
UPDATE 1 : In case you want to iterate and do some operation based on condition then do something like this.
jQuery("td[headers='name_head'] a").each(function(){
if(//your ondition){
$(this).attr('href', '');
}
});
or
jQuery("td[headers='name_head']").each(function(){
if(//your ondition){
$('a', this).attr('href', '');
}
});
UPDATE 2 : If you want to remove the entire attribute then use removeAttr('href') method which removes the entire attribute itself.
jQuery("td[headers='name_head'] a").removeAttr('href');
Why would you reinvent the wheel?
You don't need regex to achieve this, you can simply do it this way:
jQuery("td[headers='name_head'] a").attr('href', '');
It will set href to "" for all <a> elements inside td[headers='name_head'] so it will always respect your condition.
I haven't tested this code; but something like this should help, don't think you need to use regex for this;
$('a.DisableItemLink[href!=''][href]').each(function(){
var href = $(this).attr('href');
// do something with href
})
This piece of code selects all elements which have the class DisableItemLink with a location set and sets it to blank.
I am curious as to what you are trying to do in the larger scheme of things though, sounds like there might be better ways to go about it.
Reference: some good selector combinations for links

jQuery how to do the following

I've the following question, let say we have a div like this:
These are dynamically formatted divs, with the classes 'row', 'element' and 'isotope-item' are always present. Everything in between can vary per div.
What I want is to the following:
As you see the commmas are no longer there and seperate classes between the commas are now one class.
Anyone any idea?
I already have the following to remove the commas:
$('div.element').each(function () {
var _sCurrClasses = jQuery(this).attr('class');
jQuery(this).attr('class', _sCurrClasses.replace(/,/g, ' '));
});
I would advise doing this backend,but in JavaScript you could:
This will not account for the space in the words though.
You would need to pass then trough separately one by one and replace.
or store them in a data-attribute and format when you need them.
<string>
var classesFormat = classes.replace(/,/g, '');
var classesList = classesFormat.split(" ");
for(String c : classesList)
{
$("#id").addClass(c);
}
</string>
So you could create a data-attribute for each one instead.
Go through each one, format and the add to class.
<div data-id="Microsoft Office," class="test test test">
With the script
$(this).attr("data-id") // will return the string "Microsoft Office,"
or .data() (if you use newer jQuery >= 1.4.3)
$(this).data("id") // will return the Microsoft Office,
And then do your replace after that and addClass.
I don't think classes work like you think they do
the first PICTURE you posted would result in that div having the follwing classes
row
element
Microsoft
Office,
My
SQL,
Page
Rank
isotope-item
Note the , is PART of the class
You want, according to the second PICTURE
row
element
MicrosoftOffice
MySQL
Page
Rank
isotope-item
Removing , is just as you posted ... the problem is, how do you determine which spaces to remove, and which to keep?
(I posted this as an ANSWER, but I KNOW IT IS NOT AN ANSWER)

String manipulation using jQuery

I am wondering how I would remove the vowels from a word on a button click?
Here is what I am trying to do - http://www.marcia.bnmla.com/~marcia/project0.html
I need to use jQuery to remove the vowels in the second box so it displays only consonants when you click the button. I have it where it displays "MRC" as text when the button is clicked and I need to redo it using string manipulation so I can change the word to anything in my code and it will remove the vowels in that word. I am obviously new at this. Please help me!
Here is my code:
<div id="marcia_box">
<p id="marciatext">marcia</p>
<div id="marcia_boxBtn"><button id="marciaBtn">Marcia</button></div>
</div>
$("#marciaBtn").click(function() {
$("#marcia_box").css("background-color","#999");
$("#marciatext").html('mrc');
});
Do you really need jQuery? What about plain old JavaScript?
"abcdef".replace(/[aeiou]/gi, "") // => "bcdf"
How's that?
jQuery allows you to pass a function to .html, which should return a new HTML string. jQuery will pass the old HTML, so you can do something like this:
$("#marciatext").html(function(i, current) {
return current.replace(/[aeiou]/g, "");
});
demo
This one will help you now and in the future for other transformations
specially for toggling between two array keys
var c=0, text=['marcia', 'mrc'];
$("#marciaBtn").click(function() {
$("#marciatext").html( text[ ++c%2 ] );
});
As shown by Jarrett Meyer, removing the vowels has nothing with the jQuery part. But just to show you how to put it together with jQuery (since you said you is really new in it), here is a sample:
$("#marciatext").text($("#marciatext").text().replace(/[aeiou]/gi, ""));

Grab a single digit out of a big mess of html

I am grabbing a div from the document with :
var myTotal = window.document.getElementById('status').innerHTML;
which returns a big mess of HTML
<div id="foo">
<a href="bar" onclick='_gaq.push(["_trackEvent", "The", "Total",])'>
<img src="foo.gif" alt="foo" height="22px;/" width="15px;"></a>
</div>
<a href="bar" onclick='_gaq.push(["_trackEvent", "The", "Total",])'>
MY TOTAL:
<span style="font-size: 12px; color: #F3A428; font-weight:normal;"> 8 item(s) </span>
</a>
Can one of you expression wizards please show me how I can grab just the number in the span, in this example an 8 ?
Can you give the span an id and reference it directly?
If not, then this regex should return the number in the span: /<span[^>]+>\s*(\d+)/
I'm assuming that there is only ever one span in the div.
This should help you
var myTotal = window.document.getElementById('status').getElementsByTagName('span')[0].innerHTML
myTotal = myTotal.replace(/(^\d+)(.+$)/i,'$1');
In jQuery, without even getting the inner HTML it would be this:
var items = $("#status span").first().text();
items = parseInt(items, 10);
alert(items); // 8
If you control the HTML, it would be advisable to put a unique ID on the span containing the result and then it's easier to retrieve and not dependent upon the structure around it or better yet, have it output into the page as a JS variable that you can just directly read and not have to deal with the presentation.
Seen in a jsFiddle here: http://jsfiddle.net/jfriend00/UqcxS/
You can also try, just using innerText
window.document.getElementById('status').innerText.replace(/[^0-9]/gi, '');
http://jsfiddle.net/X9ffE/
Use jQuery instead, it has a lot of functions that can help you find specific elements in your page. Also, you may want to add identification for your elements like class and id.

how to highlight part of textarea html code

I want to achieve a python version web regexbuddy,and i encounter a problem,how to highlight match values in different color(switch between yellow and blue) in a textarea,there has a demo what exactly i want on http://regexpal.com,but i was a newbie on js,i didn't understand his code meaning.
any advice is appreciated
To save time you should consider using an existing library for this requirement.
Quote from here:
As textarea elements can’t render HTML, this plugin allows you to highlight text inside textarea elements.
jQuery highlightTextarea.
Demo: Codepen
Usage:
$context.highlightTextarea(options);
There is a pre element over the textarea. So when you type anything it is copying the input on the pre element, applying some filters.
For example:
<pre id="view"></pre>
<textarea id="code"></textarea>
When you type on #code it is copying the value, applying filters and adding the HTML to the #view.
var code = document.getElementById("code");
var pre = document.getElementById("pre");
(code).onkeyup = function (){
val = this.value;
val = YourRegex(val);
(pre).innerHTML = val;
};
YourRegex would be a method to match the regex and return some parsed content to the pre, allowing you to customize the appearance of the textarea (that is actually an element over it).
function YourRegex(val)
{
// This function add colors, bold, whatever you want.
if (/bbcc/i.test("bbcc"))
return "<b>" + val + "</b>";
}
#BrunoLM's solution is excellent, but might require more hacking than you're comfortable with. If you're interested (and if jQuery is already in your stack), the following plugin may be worth taking a look at:
http://garysieling.github.io/jquery-highlighttextarea/

Categories

Resources