I have a <div id="bread"></div> and I am trying to display breadcrumbs where one of the string contains Tab3 ».
Its like Tab1 > Tab2 > Tab3 » > Tab4 except that > is an arrow-right.png image.
I want to remove » or » from Tab3 ».
I want to search if the selected tab has » or » in it and if it does then I want to replace it with "" so that Tab3 » becomes Tab3.
I've tried the following but it doesn't seem to work.
$("document").ready(function() {
var crumbs = $("a.selected");
jQuery.each(crumbs, function() {
if(this != crumbs.get([0])) {
$("#bread").append(" ");
}
$("#bread").append("<img src='<c:url value="/resources/images/arrow-right.png" />' />" + " ");
var crumb = $(this).html();
var slicedCrumb;
if(crumb.indexOf(' » ') != -1) {
slicedCrumb = $(this).html().replace(' » ', '');
$("#bread").append(slicedCrumb);
}
else {
$("#bread").append(crumb);
}
});
});
I also tried to use » at the place of » but that din't seem to work either.
$("document").ready(function() {
var crumbs = $("a.selected");
jQuery.each(crumbs, function() {
if(this != crumbs.get([0])) {
$("#bread").append(" ");
}
$("#bread").append("<img src='<c:url value="/resources/images/arrow-right.png" />' />" + " ");
var crumb = $(this).html();
var slicedCrumb;
if(crumb.indexOf(' » ') != -1) {
slicedCrumb = $(this).html().replace(' » ', '');
$("#bread").append(slicedCrumb);
}
else {
$("#bread").append(crumb);
}
});
});
I've spent quite sometime reading other posts on the given subject but somehow I am not able to get it working. Could someone help me understand what am I missing here? I am using jquery-1.5.js to run this code. Do I need to use the newer version of jquery or any other library as well to get it working?
slicedCrumb = $(this).html().replace(/\»/g, '');
The important part is escaping the » character. Also I added the global (g) flag so that if there are multiple instances that match the regex, they will all be removed.
Here is a demo: http://jsfiddle.net/YXXZs/1/
UPDATE
If you want to check if a character exists before trying to replace it then you can use .match():
var text = $(this).html();
if (text.search(/\»/) > -1) {
slicedCrumb = text.replace(/\»/g, '');
}
Here is a demo: http://jsfiddle.net/YXXZs/4/
Docs for .match(): https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/match
Try using
slicedCrumb = $(this).html().replace('/[&]raquo[;]/ ', '');
Related
I've got the following script, which successfully replaces < and > with the code indicated below. The idea here is that a user would put into the text box if they want "Bold me" to appear bolded on their blog.
$('.blogbody').each(function() {
var string = $(this).html();
$(this).html(string.replace('<', '<span class="bold">'));
});
$('.blogbody').each(function() {
var string = $(this).html();
$(this).html(string.replace('>', '</span>'));
});
The problem comes with other html entities. I'm going to simply my example. I want to replace the [ html entity with a paragraph tag, but none of the lines in this script work. I've tried documenting each code that related to the '[' character.
$('.blogbody').each(function() {
var string = $(this).html();
$(this).html(string.replace('[', '<p>'));
});
$('.blogbody').each(function() {
var string = $(this).html();
$(this).html(string.replace('[', '<p>'));
});
$('.blogbody').each(function() {
var string = $(this).html();
$(this).html(string.replace('[', '<p>'));
});
$('.blogbody').each(function() {
var string = $(this).html();
$(this).html(string.replace('[', '<p>'));
});
Any thoughts on this would be greatly appreciated! Thanks!
The character '[' is not a character entity so it is not encoded. Just pass it directly to replace:
string.replace('[' , '<p>')
Hoping someone can help me it's driving me nuts.
I am using SPServices and Javascript to rewrite some links after a small content migration.
I have some HTML in a variable and I'm trying to find a string which is a specific URL and replace it with a different URL. This works:
newHTML = newHTML.replace("http://urlhere/subsite/page.aspx",newLink);
Also this works:
newHTML = newHTML.replace(new RegExp("http://urlhere/subsite/page.aspx", 'gi'), newLink);
But if I have a variable containing the same string in there it doesn't work:
newHTML = newHTML.replace(new RegExp(oldLink, 'gi'), newLink);
My oldLink variable comes from an SPServices call to another list column containing HTML, which I take the 'a' tags and put them into an array:
function rewriteLinks() {
var urlStart = "http://urlstart";
var linkContainerArray = [];
var theContent = $('.htmlContentDiv').html();
// get a tags
var aTags = ('a',theContent);
//loop through A tags and get oldLink and Text
$(aTags).each(function(){
var ID;
var itemTitle = $(this).text();
var oldLink = $(this).attr('href');
var newLink;
if(itemTitle.length > 2){
//SpService call to get ID of that item using inner text as query to SharePoint list
$().SPServices({
operation: "GetListItems",
async: false,
CAMLViewFields: "<ViewFields><FieldRef Name='Title' /><FieldRef Name='ID' /></ViewFields>",
CAMLQuery: '<Query><Where><Eq><FieldRef Name="Title" /><Value Type="Text"><![CDATA['+itemTitle+']]></Value></Eq></Where></Query>',
listName: 'AGItems',
completefunc: function (xData, Status) {
$(xData.responseXML).SPFilterNode("z:row").each(function() {
ID = $(this).attr("ows_ID");
//Now have oldLink and newID in variables - build newLink from known URL & newID
newLink = urlStart+ID;
});//response xml
}//completefunc
});//spservices
//check for empty links
if((oldLink && newLink != '') && (oldLink && newLink != undefined)){
var linkPair = [oldLink,newLink];
linkContainerArray.push(linkPair);
}
}
});
replaceLinks(linkContainerArray);
}
Then I call a function to find and replace the links (this is where my variable won't work). I've tried escaping in all combinations of the following ways:
function escapeRegExp(stringToGoIntoTheRegex) {
return stringToGoIntoTheRegex.replace(/[\/\\^$*+?.|[\]{}]/g, '\\$&');
}
function htmlEncode(value){
//create a in-memory div, set it's inner text(which jQuery automatically encodes)
//then grab the encoded contents back out. The div never exists on the page.
return $('<div/>').text(value).html();
}
function htmlEscape(str) {
return String(str)
.replace(/"/g, '"')
.replace(/'/g, "'")
.replace(/</g, '<')
.replace(/>/g, '>');
}
function escapeRegExp(stringToGoIntoTheRegex) {
return stringToGoIntoTheRegex.replace(/[\/\\^$*+?.|[\]{}]/g, '\\$&');
}
Also removed full stops and question marks from the HTML & variable to make everything simple and it's still not working.
Also tried encodeURIComponent on the HTML & oldlink variable.. still no luck
If anyone has any help for me with this at all it would be much appreciated or can maybe see what I'm missing?!
Thanks
It does not work because some the characters in the string have a special meaning in a regular expression, like \ and .. So they need to be escaped.
You can use this function:
function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
var newHTML = ' my link ';
var oldLink = 'http://someplaintext/pages/GuidelinesaspxiPageId=14495';
var newLink = 'http://urlstart?id=14495';
newHTML = newHTML.replace(new RegExp(escapeRegExp(oldLink), 'gi'), newLink);
console.log(newHTML);
See also this question.
I have a formatted text field which contains..
"this is some text node
<div class="myClass">contents....</div>
some more text node
<div class="myClass">contents....</div>
"
..like this.
Now i want to remove all the surrounding " " to those divs which has class="myClass" only i.e the " " before and after those divs.
I have gone through this link but it is not solving my problem
jquery how to find if div with specific id exists
Thanks in advance.
I might go for something like
var text = '"this is some text node <div class="myClass"> contents....</div> some more text node <div class="myClass"> contents.... </div> "';
var $ct = $('<div />', {
html: text
});
$ct.find('.myClass').each(function () {
if (this.nextSibling && this.nextSibling.nodeType == 3) {
this.nextSibling.data = this.nextSibling.data.replace(/^\s+/, '');
}
if (this.previousSibling && this.previousSibling.nodeType == 3) {
this.previousSibling.data = this.previousSibling.data.replace(/\s+$/, '');
}
})
var html = $ct.html();
Demo: Fiddle
you can replace '' instead of '& nbsp;',
$('.myClass').html($('.myClass').html().replace(' ',''));
or try like this,
$('.myClass').html(function(i,h){
return h.replace(/ /g,'');});
var text = '"this is some text node <div class="myClass"> contents....</div> "';
var $ct;
$ct = $('<pre />', {
html: text
});
$ct.find('.myClass').each(function () {
if (this.nextSibling && this.nextSibling.nodeType == 3) {
var r = this.nextSibling.data;
this.nextSibling.data = this.nextSibling.data.replace(String.fromCharCode(160), '');
var s = this.nextSibling.data;
this.nextSibling.data = this.nextSibling.data.replace(/^ /, '');
}
if (this.previousSibling && this.previousSibling.nodeType == 3) {
this.previousSibling.data = this.previousSibling.data.replace(String.fromCharCode(160), '');
this.previousSibling.data = this.previousSibling.data.replace(/ /, '');
}
})
var html = $ct.html();
alert(html);
Thanks to all. I just modified Mr. Arun P johny's code a little. And thats worked for me perfectly. In his code it was deleting blank space also, but i wanted to delete   only.
On my HTML form, users can enter their name.
Their name will then appear in a DIV as part of a book title.
The book title uses apostrophe 's (e.g. Amy's Holiday Album).
If the user enters a name which ends in a S, I don't want the apostrophe s to appear.
(e.g. it should be Chris' Holiday Album instead of Chris's Holiday Album).
I also only want this to occur if the form has a class of apostrophe. If this class does not exist, then the name should be copied as is without any apostrophe or 's'.
I know you can use slice() to get the last character of an element, so I thought I could combine this with an if statement. But it doesn't seem to work.
Here is JSFiddle
Here is my HTML:
<div><b class="title"></b> Holiday Album</div>
Here is my Jquery (1.8.3):
$(document).ready(function() {
$('.name').keyup(function() {
var finalname = text($(this).val());
var scheck = finalname.slice(-1);
var finaltitle;
if ($(".apostrophe")[0]) {
if (scheck == 's') {
finaltitle = finalname + "'";
}
else {
finaltitle = finalname + "'s";
}
$('.title').text(finaltitle);
}
else {
$('.title').text(finalname);
}
});
});
text method is not needed on
var finalname = $(this).val();
check fiddle
Use
var finalname = $(this).val();
instead of
var finalname = text($(this).val());
Simplified version
$(document).ready(function() {
//Code fires when user starts typing:
$('.name.apostrophe').keyup(function() {
if (this.value.indexOf("'s") != -1 ) {
$('.title').text(this.value.replace(/'s/g, "'"));
} else {
$('.title').text(this.value)
}
}); /* Capture Personalised Message */
});
This will also replace all occurrences of the 's with ' only.
Hope it helps!.
I need a little help with some regex I have. Basically I have a shout box that only shows text. I would like to replace urls with links and image urls with the image. I've got the basics working, it just when I try to name a link that I have problems, well if there is more than one link... check out the demo.
Named link format {name}:url should become name. The problem I am having is with shout #5 where the regex doesn't split the two urls properly.
HTML
<ul>
<li>Shout #1 and a link to google: http://www.google.com</li>
<li>Shout #2 with an image: http://i201.photobucket.com/albums/aa236/Mottie1/SMRT.jpg</li>
<li>Shout #3 with two links: http://www.google.com and http://www.yahoo.com</li>
<li>Shout #4 with named link: {google}:http://www.google.com</li>
<li>Shout #5 with two named links: {google}:http://www.google.com and {yahoo}:http://www.yahoo.com and {google}:http://www.google.com</li>
</ul>
Script
var rex1 = /(\{(.+)\}:)?(http\:\/\/[\w\-\.]+\.[a-zA-Z]{2,3}(?:\/\S*)?(?:[\w])+)/g,
rex2 = /(http\:\/\/[\w\-\.]+\.[a-zA-Z]{2,3}(?:\/\S*)?(?:[\w])+\.(?:jpg|png|gif|jpeg|bmp))/g;
$('ul li').each(function(i){
var shout = $(this);
shout.html(function(i,h){
var p = h.split(rex1),
img = h.match(rex2),
typ = (p[2] !== '') ? '$2' : 'link';
if (img !== null) {
shout.addClass('shoutWithImage')
typ = '<img src="' + img + '" alt="" />';
}
return h.replace(rex1, typ);
});
});
Update: I figured it out thanks to Brad helping me with the regex. In case anyone needs it, here is the updated demo and code (Now works in IE!!):
var rex1 = /(\{(.+?)\}:)?(http:\/\/[\w\-\.]+\.[a-zA-Z]{2,3}(?:\/\S*)?(?:[\w])+)/g,
rex2 = /(http:\/\/[\w\-\.]+\.[a-zA-Z]{2,3}(?:\/\S*)?(?:[\w])+\.(?:jpg|png|gif|jpeg|bmp))/g;
$('ul li').each(function(i) {
var shout = $(this);
shout.html(function(i, h) {
var txt, url = h.split(' '),
img = h.match(rex2);
if (img !== null) {
shout.addClass('shoutWithImage');
$.each(img, function(i, image) {
h = h.replace(image, '<img src="' + image + '" alt="" />');
});
} else {
$.each(url, function(i, u) {
if (rex1.test(u)) {
txt = u.split(':')[0] || ' ';
if (txt.indexOf('{') >= 0) {
u = u.replace(txt + ':', '');
txt = txt.replace(/[\{\}]/g, '');
} else {
txt = '';
}
url[i] = '' + ((txt == '') ? 'link' : txt) + '';
}
});
h = url.join(' ');
}
return h;
});
});
(\{(.+?)\}:)
you need the ? to make the regex become "ungreedy" and not just find the next brace.
EDIT
However, if you remove the {yahoo}: the second link becomes null too (seems to populate the anchor tag, just no attribute within). This almost seems to be a victim of using a split instead of a replace. I would almost recommend doing a once-over looking for links first, then go back around looking for images (I don't see any harm in off-linking directly to the image, unless that's not a desired result?)