Search code examples
javascriptsubstr

JavaScript - Get string from position till end of line / return character


I have a string, it gets squished into one line with a (return?) character, but should be like this:

Service Type: Registration Coordinator

Authorized Amount: $4
Authorized Mileage: $1.25

I want to get 'Registration Coordinator' or whatever is there till the end of the line, so I tried this:

var service_type = t_var.description.substr(t_var.description.indexOf('Service Type: ') +14,t_var.description.indexOf('\n'));

But it returns:

Registration Coordinator

Authorized A

Here is how the original string was created before being posted to the DB, I'm trying to work with it after it has been read back from the DB:

var fullDescription = "Service Type: " + that.current_wo_data.service_partner.skill + "\n\n";
fullDescription += '\nAuthorized Amount: $' + that.$('#authorized_amount').val();
fullDescription += '\nAuthorized Mileage: $' + that.$('#authorized_mileage').val();

Thanks


Solution

  • There is a difference between substr and substring (don't ask me why)

    .substr(start_pos, number_of_chars);
    "abcdef".substr(2, 3) returns "cde"
    .substring(start_pos, end_pos);
    "abcdef".substr(2, 3) returns "c"
    

    You are using start_pos and end_pos with the function substr. That's asking for trouble ;)

    var service_type = t_var.description.substr(t_var.description.indexOf('Service Type: ') +14,t_var.description.indexOf('\n'));
    

    Should be

    var service_type = t_var.description.substring(t_var.description.indexOf('Service Type: ') +14,t_var.description.indexOf('\n'));