Converting pre to divs - javascript

How would you proceed to transform this :
<pre>
key 1 value 1
key 2 value 2
value 2.2
key 3 value 3
value 3.1
value 3.2
value 3.3
key 4 value4.1 value4.5
</pre>
To this :
<div><pre>
key 1 value 1
</pre></div><div><pre>
key 2 value 2
value 2.2
</pre></div><div><pre>
key 3 value 3
value 3.1
value 3.2
value 3.3
</pre></div><div><pre>
key 4 value4.1 value4.5
</pre></div>
Namely : remplacing continuous blank line*s* (could contains space/tabs and multiples linefeed) to </pre></div><div><pre>
I tried :
var txt = $('pre').text();
txt = txt.replace(/(\r\n|\n|\r)/gm, "</pre></div><div><pre>");
$('div#test').append(txt);
Partially work : each line are changed, I loose my blocks.
Are <pre> line break stocked as \r ? \n ? (all OS? all browsers?)
What would be a good regex to do this?
Any other way you would suggest me to proceed with?

parse the text so you get a list of lines of text
trim each line
wrap each line in <div><pre> tags
concatenate the results together
I would do a remove of the prexisting pre element altogether after parsing out the text. So instead of "transforming" it just extract the text and build a different element altogether.

That does it for me. It could be better:
$(document).ready(function(){
var lines = $('pre').html().split(/\n\s*\n/);
$('pre').remove();
for(i = 0; i < lines.length; i++){
if($.trim(lines[i].length) > 0){
var preDiv = $('<pre />');
var keyDiv = $('<div />');
preDiv.append(keyDiv);
keyDiv.html(lines[i]);
$('body').append(preDiv);
}
}
});
It doesnt address any whitespace. You can remove it with trim() in the line keyDiv.html("key" + $.trim(lines[i]))

You can use jQuery's wrap function
$('pre').text($.trim($(this).text()).wrap('<div></div>');

Related

How to get jQuery animateNumber to pull value dynamically?

I am trying to implement jQuery animateNumber, and I have it working like the demo just fine. However, I want to modify it so that it pulls the number from the HTML, rather than setting it in the script. I tried the following, but it just shows "NAN." What am I doing wrong?
<div class="stat-title animate-number">$16,309</div>
<script>
$('.animate-number').each(function(){
var value = new Number;
// Grab contents of element and turn it into a number
value = $(this).text();
value = parseInt(value);
// Set the starting text to 0
$(this).text('0');
$(this).animateNumber(
{
number: value,
},
1000
)
});
</script>
ParseInt is failing because of the $ character. Also, the comma is messing with parseInt and giving you the value 16 instead of 16309. After that, the animation seems to be working. Also, you don't necessarily have to replace it with 0 since animateNumber automatically starts from 0. Here's my work so far on JSfiddle:
http://jsfiddle.net/0m9828kn/1
$('.animate-number').each(function(){
var value = $(this).text();
value = value.substring(1, value.length);//Remove $ sign
value = value.replace(/,/g, "");//Remove all commas
value = parseInt(value);
//$(this).text("0"); //This part isn't actually necessary
$(this).animateNumber(
{
number: value
},
1000
)
});
Looks like the problem is that ParseInt is choking on the dollar sign. Then when you remove that, it only reads up to comma and animates to 16. Take them both out, and it works.
value = $(this).text().replace(/[\,\$]/g,'');
But, you'll need to include this option to get your comma back:
var comma_separator_number_step = $.animateNumber.numberStepFactories.separator(',')
$(this).animateNumber(
{
number: value,
numberStep: comma_separator_number_step
},
1000
)
To get your dollar sign back, you could change your html to something like this:
<div>$<span class="stat-title animate-number">16,309</span></div>

Increase value of digit within HTML string (jQuery)

I have a bunch of images in a folder which are all named as numbers. The first one is displayed on document load.
<img src="image/01.jpg" />
I want to use jQuery to flick through the images. In other words, I want to convert the HTML to a string and then increase the value of what is currently "01".
So far I have:
$(document).ready(function(){
$("button").click(function(){
var $n = $("img").html(htmlString(17));
$n.val(Number($n.val())+1);
});
});
The bit that I'm sure I'm completely wrong on is the selecting of the digit (i.e delcaring var $n. I've tried to convert the HTML to a string there and count along the characters but I'm not even sure if that's the right route to be taking; I can't find anything similar anywhere.
Thanks.
img element doesn't have html content, apart from that you are using html as setter not getter. You can replace the src attribute's value using replace method:
$('img').prop('src', function(_, src) {
return src.replace(/\d+/, function(n) {
var num = +n + 1;
return num.toString().length === 1 ? '0' + num.toString() : num;
});
});
http://jsfiddle.net/Bb84Q/
You can just
1)catch the src value in a js variable
2) using substr function get rid of the "image/" part.
3) Then using split() on "." take the first array slot's value.
4)Convert that to integer using intVal() and
5) then increment the value
var source = "image/01.jpg";
var number = source.split(".")[0].split("/")[1];
number = (number *1) + 1
var newsource = "image/" + number + ".jpg";
this is how you'd actually get source
var source = $("img").attr('src');
just realized that this will make "image/2.jpg" , you could use a data-number attribute, you could re-name the images that are 1 - 9 , but this gives you an idea

Cross-browser ready new line counter in Javascript

I got 2 questions:
My function looks like that
function count() {
var value = ids.val();
return (value == '') ? 0 : value.replace(/\s,?|,$/g, '').split(/\r\n|\r|\n/).length;
}
What I wanna do is, to skip whitespaces and count all new lines
For ex:
85
96
75
<whitespace>
76
count() must return 4 not 5. How can I modify my function?
How to convert line break seperated words/numbers to comma seperated content?
For ex:
85
96
75<whitespace>
<whitespace>
76
I want to trim all whitespaces and convert whole content into something like that 85,96,75,76. How can I do it ?
The easiest way would be .filter($.trim).map($.trim), which first removes any whitespace entries, and then cleans the remaining entries by removing surrounding spaces: http://jsfiddle.net/BtLzf/1/.
var vals = ids.val()
.split(/\r\n|\r|\n/)
.filter($.trim)
.map($.trim);
vals.length; // 4
vals.join(); // 85,96,75,76
.filter/.map are ES5 which means you'll need a shim for older browsers.
I think that you will need to do a loop for checking the length of each line, because in this case you're getting the number of end-of-line characters, which is 5 even if the line is empty... Getting this iterator you can also get the comma-list
I'd suggest using a regex pattern that cleans things up a bit better.
Perhaps:
^(\d+)\s?$
$(function(){
var matches = $('#txtInput').text().match(/^(\d+)\s?$/mg);
$('#txtResult').text(matches.join(','));
});​
Working Example:
http://jsfiddle.net/mZ97L/
What about something like this?
// Count of items in the list.
function count(){
var list = delimitedList();
return list.split(",").length;
}
// Get list separated by comma.
function delimitedList(){
var value = ids.val();
return value.replace(/\s+/g, ",");
}
http://jsfiddle.net/wT23h/2/

How do i get the length of innerHTML (total characters) in JavaScript?

I'm trying to get the length of the characters that I attain from innerHTML and it's kind of come down to last resort, but can't seem to find a more efficient way as the data is inside a slider that I'm trying to use to get the lower value and higher value.
var lvalue=document.getElementById("lval").innerHTML;
then I'm spiting the string in the spaces:
var larr=lvalue.split(" ");
The innerHTML value is something like this "2413dsk 134dfa134".
And when i use larr[0].length, I get 1 when I need 7. Is there a solution?
I think it would go something like this:
var lvalue = document.getElementById("lval").innerHTML;
var larr = lvalue.split(' ');
var len = 0;
// For each iterates over the index of arrays
for(var i in larr) {
len += larr[ i ].length // Acummulate the length of all the strings
}
Or alternatively you could count the spaces first and then substract it from the total length.
// Some people argue about extending the native objects
// but in this case I think this method is a natural fit.
String.prototype.count = function( character ) {
var l = 0;
// `this` refers to the string itself
for(var c in this) n = this[ c ] === character ? ++n : n;
return n;
}
An then use it like so:
var lvalue = document.getElementById("lval").innerHTML;
// Subtract total length minus the number of spaces
var len = lvalue.length - lvalue.count(' ');
This might be caused by a preceding or leading space.
Try trimming the extra spaces :
var lvalue=document.getElementById("lval").innerHTML.replace(/^\s+/gi,'').replace(/\s+$/gi,'');
var larr=lvalue.split(" ");
I didn't see any problem with your code. I run a test here: http://desdegdl.com/lval.html
Probably, you have one or more spaces at the begining of lval's inner HTML.
If there is someone like me that doesn't want to use JQuery, here is a example in javascript (only)...
The files
The html file...
<!-- start body -->
<body>
<!-- start section -->
<section id="bar"></section>
<!-- end section -->
</body>
<!-- end body -->
The javascript file...
/* start - wut element do ya wanna get? */
foo = document.getElementById('bar');
/* end - wut element do ya wanna get? */
/* start function */
function isEmpty(){
if (foo.innerHTML.length === 0) {
/* your code here */
}
}
/* end function */
What I did
In the HTML
Quite simple, I just created a section and assigned an ID on it. This ID will be used to call her in our javascript.
In the JavaScript
In the var fooI I called the section whose I gave an ID.
After it I created a function that "do something" if the length of a element is equal zero.
Considerations
It works, but if you have a space or a line break the code will not consider it as "empty"...

Doing assignment in VBscript now.. Need to give positions of each "e" in a string

I've done this in JavaScript but needless to say I can't just swap it over.
In Jscript I used this:
var estr = tx_val
index = 0
positions = []
while((index = estr.indexOf("e", index + 1)) != -1)
{
positions.push(index);
}
document.getElementById('ans6').innerHTML = "Locations of 'e' in string the are: "
+ positions;
I tried using the same logic with VBS terms, ie join, I also tried using InStr. I'm just not sure how to yank out that 'e'... Maybe I'll try replacing it with another character.
Here is what I tried with VBScript. I tried using InStr and replace to yank out the first occurance of 'e' in each loop and replace it with an 'x'. I thought that maybe this would make the next loop through give the location of the next 'e'. -- When I don't get a subscript out of range 'i' error, I only get one location back from the script and its 0.
(6) show the location of each occurence of the character "e" in the string "tx_val" in the span block with id="ans6"
countArr = array()
countArr = split(tx_val)
estr = tx_val
outhtml = ""
positions = array()
i=0
for each word in countArr
i= i+1
positions(i) = InStr(1,estr,"e",1)
estr = replace(estr,"e","x",1,1)
next
document.getElementById("ans6").innerHTML = "E is located at: " & positions
What can I do that is simpler than this and works? and thank you in advance, you all help a lot.
EDIT AGAIN: I finally got it working right. I'm not 100% how. But I ran through the logic in my head a few dozen times before I wrote it and after a few kinks it works.
local = ""
simon = tx_val
place=(InStr(1,simon,"e"))
i=(len(simon))
count = tx_val
do
local = (local & " " & (InStr((place),simon,"e")))
place = InStr((place+1),simon,"e")
count = (InStr(1,simon,"e"))
loop while place <> 0
document.getElementById("ans6").innerHTML= local
InStr has slightly different parameters to indexOf:
InStr([start, ]string, searchValue[, compare])
start: The index at which to start searching
string: The string to search
searchValue: The string to search for
Also note that Visual Basic indexes strings beginning at 1 so all the input and return index values are 1 more than the original JavaScript.
You can try split(). For example a simple string like this:
string = "thisismystring"
Split on "s", so we have
mystring = Split(string,"s")
So in the array mystring, we have
thi i my tring
^ ^ ^ ^
[0] [1] [2] [3]
All you have to do is check the length of each array item using Len(). For example, item 0 has length of 3 (thi), so the "s" is at position 4 (which is index 3). Take note of this length, and do for the next item. Item 1 has length of 1, so we add it to 4, to get 5, and so on.
#Update, here's an example using vbscript
thestring = "thisismystring"
delimiter="str"
mystring = Split(thestring,delimiter)
c=0
For i=0 To UBound(mystring)-1
c = c + Len(mystring(i)) + Len(delimiter)
WScript.Echo "index of s: " & c - Len(delimiter)
Next
Trial:
C:\test> cscript //nologo test.vbs
index of str is: 8

Categories

Resources