wrap numbers in span and .not() - javascript

This is similar to other questions, but it's about something specific.
The first example doesn't do anything (breaks)
The second example works except that it hacks up html tags (specifically a tags) as well, so href="something with numbers" get hashed and then the whole thing falls apart
Then I get anchors that have their href attributes hashed up with span tags. Obviously that isn't what I want. What am I doing wrong? There must be some way to put all numbers and ", - : ()" inside a span without hashing up the html tags themselves.
$('#main-content p').contents().not("a").html(function(i, v) {
return v.replace( /([0-9(),-:]+)/g , '<span class="number">$1</span>');
});
$('#main-content p').html(function(i, v) {
return v.replace( /([0-9(),-:]+)/g , '<span class="number">$1</span>');
});

You are replacing all number. You need to only select the text nodes within the element. This code is not tested, but should work.
EDIT: You have to also call .contents(). See this answer
EDIT 2: I got it working in this FIDDLE. Let me know what you think. Did you mean to replace special characters as well as numbers?....because that is what is currently happening per your original regEx.
$('p').contents().filter(function () { return this.nodeType === 3; }).each(function(){
$(this).replaceWith($(this).text().replace( /([0-9(),-:]+)/g ,
'<span class="number">$1</span>'));
});

Related

Replace non-code text on webpage

I searched through a bunch of related questions that help with replacing site innerHTML using JavaScript, but most reply on targetting the ID or Class of the text. However, my can be either inside a span or td tag, possibly elsewhere. I finally was able to gather a few resources to make the following code work:
$("body").children().each(function() {
$(this).html($(this).html().replace(/\$/g,"%"));
});
The problem with the above code is that I randomly see some code artifacts or other issues on the loaded page. I think it has something to do with there being multiple "$" part of the website code and the above script is converting it to %, hence breaking things.using JavaScript or Jquery
Is there any way to modify the code (JavaScript/jQuery) so that it does not affect code elements and only replaces the visible text (i.e. >Here<)?
Thanks!
---Edit---
It looks like the reason I'm getting a conflict with some other code is that of this error "Uncaught TypeError: Cannot read property 'innerText' of undefined". So I'm guessing there are some elements that don't have innerText (even though they don't meet the regex criteria) and it breaks other inline script code.
Is there anything I can add or modify the code with to not try the .replace if it doesn't meet the regex expression or to not replace if it's undefined?
Wholesale regex modifications to the DOM are a little dangerous; it's best to limit your work to only the DOM nodes you're certain you need to check. In this case, you want text nodes only (the visible parts of the document.)
This answer gives a convenient way to select all text nodes contained within a given element. Then you can iterate through that list and replace nodes based on your regex, without having to worry about accidentally modifying the surrounding HTML tags or attributes:
var getTextNodesIn = function(el) {
return $(el)
.find(":not(iframe, script)") // skip <script> and <iframe> tags
.andSelf()
.contents()
.filter(function() {
return this.nodeType == 3; // text nodes only
}
);
};
getTextNodesIn($('#foo')).each(function() {
var txt = $(this).text().trim(); // trimming surrounding whitespace
txt = txt.replace(/^\$\d$/g,"%"); // your regex
$(this).replaceWith(txt);
})
console.log($('#foo').html()); // tags and attributes were not changed
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo"> Some sample data, including bits that a naive regex would trip up on:
foo<span data-attr="$1">bar<i>$1</i>$12</span><div>baz</div>
<p>$2</p>
$3
<div>bat</div>$0
<!-- $1 -->
<script>
// embedded script tag:
console.log("<b>$1</b>"); // won't be replaced
</script>
</div>
I did it solved it slightly differently and test each value against regex before attempting to replace it:
var regEx = new RegExp(/^\$\d$/);
var allElements = document.querySelectorAll("*");
for (var i = 0; i < allElements.length; i++){
var allElementsText = allElements[i].innerText;
var regExTest = regEx.test(allElementsText);
if (regExTest=== true) {
console.log(el[i]);
var newText = allElementsText.replace(regEx, '%');
allElements[i].innerText=newText;
}
}
Does anyone see any potential issues with this?
One issue I found is that it does not work if part of the page refreshes after the page has loaded. Is there any way to have it re-run the script when new content is generated on page?

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

Slice first character from paragraph element, replace content and add class. jQuery

I am close to getting this function working, but not quite there yet.
The basic logic says find any p element that contains "+", strip the "+" from the text and try and replace the existing content with the new content and add a class.
Initially I had all of the matched elements being returned and concatenated into a single paragraph. So I tried to create an each function. I am now seeing the right results in the console, but I am not sure how to replace the content for the matched paragraph only (using $(this)).
I've made a fiddle here: http://jsfiddle.net/lharby/x4NRv/
Code below:
// remove bespoke text and add class
$qmarkText = $('.post p:contains("+")').each(function() {
$qStr = $(this).text().slice(1);
$qmarkText.replaceWith('<p class="subhead-tumblr"' + $qStr + '</p>');
console.log($qStr);
});
I know that $qmarkText is not quite but not sure how to fix this, have tried several variations.
Hopefully someone can help me out.
You could use following snippet:
// remove bespoke text and add class
$qmarkText = $('p').filter(function () {
return $(this).text().substring(0, 1) === "+"
}).each(function () {
$qStr = $(this).text().slice(1);
$(this).replaceWith('<p class="subhead-tumblr">' + $qStr + '</p>');
});
DEMO
This avoid using :contains() which will match even character '+' is inside content text, not only at the beginning.

What is the Javascript Regexp for finding the attributes in a <span> tags?

I have a <div contenteditable="true> that I am trying to use to get text from users. I would use a simple <textarea>, but I need line-breaks and eventually lists and tables etc. I am trying to build something that is semi a rich-text editor, but not a full fledged one. I do not want to use a rich text editor.
I am trying to eliminate the attributes on <span> tags from the text that is typed into the <div contenteditable="true> . Is there a way to do that with Regexp? I was having difficulties coming up with a Regexp because I can't figure out how to make it so that the string starts with <span and ends with > and any number of characters can be in between. Is there a way to combine that in one Regexp? I came up with /^<span >$/ but that does not work because there is no division between the two strings. Would something like this work: /^[<span][>]$/g?
Use DOM functions for it. Here's some code using jQuery to make it easier and nicer to read:
$('#your-div span').each(function() {
var elem = this, $elem = $(this);
$.each(elem.attributes, function(i, attr) {
if(attr) {
$elem.removeAttr(attr.name);
}
});
});
Demo: http://jsfiddle.net/ThiefMaster/qfsAb/
However, in your case you might want to remove attributes not only from spans but from all elements unless the attribute is e.g. align or href.
So, here's some JS for that: http://jsfiddle.net/ThiefMaster/qfsAb/1/
$('#your-div').children().each(function() {
var elem = this, $elem = $(this);
$.each(elem.attributes, function(i, attr) {
if(attr && attr.name != 'href' && attr.name != 'align') {
$elem.removeAttr(attr.name);
}
});
});
Parse the HTML and then strip out the attributes afterwards. If you're doing this in a browser, you have a high grade HTML parser right at your disposal (or you have IE), so use it!
I made a working demo at http://jsfiddle.net/b3DSQ/
$('#editor span').each(function(i, el) {
var attrs = el.attributes;
$.each(attrs, function(i, a) {
$(el).removeAttr(a.name);
});
});
[I changed an earlier version which copied the contents into memory, edited, and then replaced - hadn't realised that the stuff typed into the div was automatically valid in the DOM].
Try this:
your_string.replace(/<span[^>]*>/g, '<span>');
This will break however if the user writes something like <span title="Go > there">

Replace a empty space with " " using Jquery

I am looking around on the web but I am not finding anything useful. :(
I am having a problem that I don't understand. I am sure that I am doing something wrong, but I don't know well the syntax of jQuery to understand what is that I am not doing right.
I am using animations with JS and CSS 3, and I am having troubles with empty spaces between the words, and to solve this problems I have to find a way to substitute chars inside a string of text with something else. Like an empty space with a , or as a test that I was trying to do a "n" with a "xxxxx".
What I think that I am doing is:
when the page is loaded
Modify the string of any paragraph with the class .fancy-title that contains "n" with a text "xxxxx"
So:
$(document).ready(function(){
for(i=0; i< myLength+1; i++){
var charCheck = $(".fancy-title").text()[i];
if(charCheck == "n"){
charCheck.replace("n", "xxxxxxxx");
}
}
});
But I receive an error that it said:
charCheck.replace("n", "xxxxxxxx"); it is not a function
I am using jquery
and other scripts that are based on jquery to make animations, rotation and scaling... and they are all in the HEAD with jquery first to load.
What am I doing wrong? Manipulation in jQuery does it need a specific .js extension? I understood that was in the basic capability of jQuery, and looking at other examples all creates me the same kind of error.
I even tried
if(charCheck == "n"){
$(".fancy-title").text()[i] == " "
}
But simply the modification it is not applied on the page. I tried with innerHTML as well :(
I feel so incompetent...
Thank you in advance for any help.
$(document).ready(function(){
$(".fancy-title").each(function(i){
var text = $(this).html();
$(this).html(text.replace(/ /g, " "));
})
});
You have no problem with the replace part :).
$(document).ready(function(){
$(".fancy-title").each(function () { //for all the elements with class 'fancy-title'
var s=$(this).text(); //get text
$(this).text(s.replace(/n/g, 'xxxxxxxx')); //set text to the replaced version
});
});
Just a quick example, hope it works.
Have you tried the css style white-space:pre instead of replacing ' ' with ' '?
http://de.selfhtml.org/css/eigenschaften/ausrichtung.htm#white_space
It seems you are trying to replace a single character with a new string.
You might be able to get the right result by dropping the iteration and simply call .replace on the jQuery-object.

Categories

Resources