Forum Moderators: open

Message Too Old, No Replies

how do I find a CR at the end of a string?

         

txbakers

11:45 pm on Feb 8, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



User can enter a list of names separated by CR (with the enter key) in a textarea as follows:

Bob Jones
Steve Wilson
Pete Hummer
Sally Smith

Four names.
But if the user enter one more CR at the end of the list my code reads 5 names.

var names = String(Request("names"));
var mbmrs = String(names).split("\r");
var nummbr = mbmrs.length;

I'm trying to find that "\r" using lastIndexOf, or even charAt or charCodeAt but it doesn't find it at the end of the string so I can adjust nummbr.

Any thoughts?

[edited by: txbakers at 11:55 pm (utc) on Feb. 8, 2004]

txbakers

11:54 pm on Feb 8, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Well, I found a solution, but is there a better way?

if (names.lastIndexOf("\r") > -1) {
var bill = names.length -1;
bill--;
names = names.substr(0,bill);
}

this gives me the correct number of names. But why do I need to take the length down one, then decrement bill again? That seems like I would need to take it down twice.

If I use bill = names.length - 2 it cuts off the last letter of the last name.

Purple Martin

12:58 am on Feb 9, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



An alternative would be to populate the array first (as you do in your first post) and then loop through the array removing any items that contain zero-length strings. This has the advantage of also removing any extra blank lines in the middle of the list of names. Have a play with the split, splice, shift and shunt methods.

txbakers

1:21 am on Feb 9, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



that's a great idea! Thanks.