JQuery to Trim leading white space only? - javascript

I am theming a JSP app that has a table header with dynamically generated data (I think it's called Jasper Reports?) and I don't have access to any template files for the output. I've gotten things to look pretty good with a little JQuery foo.
But I am still having one issue, there seems to be white space in some span tags within the headers td > spans:
<td><span> My Heading</span></td>
Note the white space before the word "My".
I found this nifty bit of code to trim white space but the issue is that it takes all white space out.
var pane = $('span');
pane.val($.trim(pane.val()).replace(/\s*[\r\n]+\s*/g, '\n')
.replace(/(<[^\/][^>]*>)\s*/g, '$1')
.replace(/\s*(<\/[^>]+>)/g, '$1'));
So now using this code, it ends up as:
<td><span>MyHeading</span></td>
Ideally I would like to modify it so just the first bit of white space is removed but none after that.

Use .text() to get the string value.
var pane = $('span');
pane.html($.trim(pane.text()));
http://jsfiddle.net/gaboesquivel/cHevR/
Edit:
the above code won't work as it overwrites the text if it there's more than 1 span in the document
You need to iterate the array of spans
//array of all the spans that are children of a td element
var spansArray = $('td > span');
//iterate the array
spansArray.each(function() {
var $this = $(this);
$this.html($.trim($this.text()));
});​
http://jsfiddle.net/gaboesquivel/cHevR/2/

Try this:
.replace(/^\s+/g, "");
That should trim any whitespace at the beginning of the string. Alternatively, you can make it trim trailing whitespace using a slightly different expression. See here:
http://www.toptip.ca/2010/02/javascript-trim-leading-or-trailing.html
Here's the example so you can see how it works:
http://jsfiddle.net/CkMPH/

For the only first space to be removed you need that code
var pane = $('span');
pane.text(pane.text().replace(/^\s/, ''));
http://jsfiddle.net/P9jSL/

Related

Replace HTML between two tags

What I want to do is replace what is in between two HTML tags.
I'm using this as a reference but I'm still encountering problems:
REFERENCE
This is what I've tried:
el.getValue().replace(/<form.+<\/form>/, "<div></div>");
I need to replace all my form tags dynamically.
If you use jQuery, just retrieve the parent element of what you'd like to be replaced, and replace the content with the .html() function.
Ex:
var formParentElement = $('#formParentElement');
formParentElement.html("<div>my new content</div>");
If you don't use jQuery:
var formParentElement = document.getElementById("formParentElement");
formParentElement.innerHTML = "<div>my new content</div>";
The example assumes the parent element of your form has an ID with value "formParentElement".
Yeah. I found a solution.
el.getValue().replace(/<form[\s\S]*?<\/form>/, "<div></div>");
Explanation by #[James G]:
[\s\S]*? means [any character including space and line breaks]any number of times, and the ? makes the asterisk "not greedy," so it will stop (more quickly) when it finds </form>.
Reference

jQuery append hrefs to mulitple words in div

I have a div with a class name (.product) and what i want to do is find multiple different words and for each word append/replace them with a href link or span etc.
There would be multiple different words to append to so it would most likely be a foreach run.
I have tried the code below but just cant get it to stick as its only replacing the whole last word variable in the script.
jQuery('.product').each(function(){
var word1 = jQuery(this).text().replace(/word1/g,"<span>word1</span>");
jQuery(this).html(word1);
});
jQuery('.product').each(function(){
var word2 = jQuery(this).text().replace(/word2/g,"<span>word1</span>");
jQuery(this).html(word2);
});
If this is not possible with jQuery/JS, what about php, how would I scan through a database text area value/content and replace foreach variable(word) and replace with href link?
Any help would be appreciated.
cheers
Your attempt looks good, it is just missing one bit. Rather than changing the text and pushing it into the HTML, try changing the text in the HTML and pushing the HTML back ... and put correct html in (</span>) ...
jQuery('.product').each(function(){
var word1 = jQuery(this).html().replace(/word1/g,"<span>word1</span>");
jQuery(this).html(word1);
});
jQuery('.product').each(function(){
var word2 = jQuery(this).html().replace(/word2/g,"<span>word1</span>");
jQuery(this).html(word2);
});
I suppose you're wanting to wrap words with <span> tag. You can do the below using html with function overload and replacing words with regex. $0 means the matched word.
jQuery('.product').each(function() {
$(this).html(function() {
return $(this).text().replace(/\w+/g, "<span>$0</span>");
});
});

Javascript : Replace Detect a string and replace html in a div after changing color

I am trying to change color of a part of strings. I have a list of DOM elements, and for each of them, the text can contain some hashtags. I would like to put in color all hashtags words which could be found in the text.
Here is the begin of the code :
var listOfText = document.getElementsByClassName("titleTweet");
for (var nodetext in listOfText) {
var divContent = listOfText[nodetext].innerHTML;
if (divContent.indexOf("#") !== -1) {
// Do job here
}
}
For example, divContent can be equals to "Hello my #friends ! How are you ?"
I would like to update the dom elements to put in red color the word "#friends".
I don't know how to do that using javascript or jQuery.
You can use a regexp to find the hastags and wrap them with html. Then use the .html() method to replace the original element's html with the new string.
Example snippet
$('#myDiv').replace(/#[a-z0-1A-Z]+/g, '<span style="color: red;">$&</span>'));
Working example - http://jsfiddle.net/4p4mA/1/
Edited the example to work on all divs on the page.
Note: This will only work so long as your element only contains text, because it is replacing all the child nodes with its text value.
use regex for this, find text having hashtag and replave that in span tag for each element.
$('.titleTweet').each(function(){
var $this=$(this);
$this.html($this.text()
.replace(/#[a-z0-1A-Z]+/g, '<span style="color: red;">$&</span>'));
});
See demo here
.innerHTML is a poor basis to starting replacing text. You'll want to navigate down to the text nodes and use .nodeValue to get the text. Then you can start splitting up the text nodes.

How to preserve whitespace in dynamically added javascript DOM element without using CSS?

When adding in text with small whitespace appended to it for alignment purposes the whitespace is trimmed off (the whitespace is added in c# so by the time it gets to front end Javascript it cannot be edited - it would be nice to just use some CSS to do this but it is not an option).
Here is what I tried so far:
var zlp = document.getElementById("testDiv")
zlp.innerHTML = "hello hello"
var zzz = document.createTextNode("hello hello")
zlp.appendChild(zzz)
<div id="testDiv"></div>
Both of which produce hello hello.
White space characters are usually collapsed in HTML (by default).
You can replace it with the entity:
var text = text.replace(/\s/g, ' ');
\s will match any white space character, such as space, tab and new line. If you only want to replace space, use / /g instead.
Other options which avoid string manipulation:
Put the text in a pre element.
Set the CSS 2 white-space property to pre as #Esailija pointed out. You can always add CSS properties dynamically to elements, they don't have to be specified in a style sheet.
use
zlp.innerHTML = "hello hello";
Like everyone else just said.
use a html tag 'pre'
Example:
<pre>
A line
A line with indent
</pre>
result:
A line
A line with indent
White space is collapsed in HTML. It's not a JS issue, the same would happen if you typed that manually in the HTML document. You need to replace the spaces with
zlp.innerHTML = "hello hello".replace( / /g, " " );

Remove CSS selectors and it's related properties if needed

I am trying to remove specific CSS selectors, and if there is no more selectors for a list of properties than the script removes it...
I was able to get a part of the script working: http://jsfiddle.net/jnbdz/MarRr/5/
Here is the code:
$$('button')[0].addEvent('click', function(){
var css = document.id('css').get('text');
var newCss = css.replace(/(\n|\r|\s\s)/g, "")
.replace(/(,\s*body\s*(?={)|,\s*body\s*(?=,)|body\s*,|,\s*head\s*(?={)|,\s*head\s*(?=,)|head\s*,)/gi, "")
.replace(/(body\s*(?={)|head\s*(?={))/gi, "")
.replace(/(^\{[^}]*?\}|\}\s*\{[^}]*?\})/gim, "");
document.id('cleancss').set('text', newCss);
});
The problem is that if I remove the line breaks the script I wrote wont be able to remove the properties that are not related to any selectors...
If I keep the line breaks it works...
Also, I would like to know from coders that are good with ReGex if my code is good...
Thanks a lot in advance for any help.
In the last replace you're using the multiline flag. That can't work, if you have only one line, which you do after the first replace. So lets keep the linebreaks first and remove them after the removal of the selectors.
You also can simplify the regexes a bit. Use x(?=a|b) instead of x(?=a)|x(?=b). You also don't need the lazy match [^\}]*?.
Below is a working example. For clarity I only removed the body selector.
$$('button')[0].addEvent('click', function(){
var css = document.id('css').get('text');
var newCss = css
// replace multiple tabs or spaces by one
.replace(/( |\t)+/g, " ")
// remove space at beginning of line
.replace(/(^\s)/gm, "")
// remove body in selector lists
.replace(/(,\s*body\s*(?={|,)|body\s*,)/gi, "")
// remove body before {
.replace(/(body\s*(?={))/gi, "")
// remove rules without selector
.replace(/[\n\r]+\{[^\}]*\}/g, "")
// remove linebreaks
.replace(/[\n\r]+/g, "");
document.id('cleancss').set('text', newCss);
});
You could further compress the stylesheet by removing spaces in front of { or after : and ,

Categories

Resources