...

View Full Version : regexp expression help! [code inside]



mseeley
12-19-2003, 04:59 PM
Hi everyone, this is my first post, but not first javascript! :) I'm hoping the members here will be able to help me solve this.

Basically a system that i'm building allows clients to copy columns from excel, paste into a textarea, and create an unordered list (within a div) from the pasted values.

I've got it working but spliting the value string on linebreaks, then iterating through the resulting array. Unfortunately this doesn't scale well when the client pastes thousands of rows. So i'm trying to take the split/iterate approach out of the formula by doing a global regular expression replace.

The regular expression should be able to match the first non whitespace character on a line up to the line break (\n), match this to $1 and then wrap $1 with list item tags.

I've attached a zip containing an .html and .xls example of what i've been working on, javascript and sample data is also posted below.

Data


123456
123457
123458
123459
123460
123461
123462
123463
123464
123465


Script


<SCRIPT LANGUAGE="JavaScript1.2">
function regExpTest(){
var s = document.getElementById('input').value;
var re = new RegExp('(*)\n', 'g');
newstr = s.replace(re, '<li>$1</li>');
alert(re.test(s));
alert(newstr);
}
</SCRIPT>
<body>
<textarea name="input" rows="10" id="input"></textarea>
<a href="#" onclick="regExpTest();">Test</a>


Thanks, this has been irking me for too long! & Sorry for the long message.

Thanks

Matt

nolachrymose
12-19-2003, 06:49 PM
Try this:


var re = /(\w+)\n?/gi;
newstr = s.replace(re, '<li>$1</li>');

Hope that helps!

Happy coding! :)

mseeley
12-19-2003, 07:22 PM
thanks for the help, i really appreciate the reply!

i was just coming back to post my final code, got it working thanks to ray326 at webdeveloper.com.

i used the code he posted and finished the script below. its pretty slick, processing all 10000 values pasted from the excel spreadsheet takes less than 2 seconds! :)

thanks for the help, the snippet i've been working on is below.


<SCRIPT LANGUAGE="JavaScript1.2">
function regExpTest(){
var s = document.getElementById('input').value;

// convert to csv
var csv_re = new RegExp('\r\n', 'g');
var csv_str = s.replace(csv_re,', ');

// convert to list
var list_re = new RegExp(/(\w+)/gm);
var list_str = '<ul id="customList">' + s.replace(list_re,'<li>$1</li>') + '</ul>';

// output to ui
document.getElementById('input').value = csv_str;
document.getElementById('list').innerHTML = list_str;
document.getElementById('count').innerHTML = document.getElementById('customList').childNodes.length;
}
</SCRIPT>
<body>
<a href="#" onclick="regExpTest();">Test</a>
<br>
<textarea name="input" rows="10" id="input"></textarea>
<br>
Count: <span id="count"></span>
<br>
<div id="list"></div>
</body>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum