ebsp
ebsp

Reputation: 102

Regular expressions removing last letter from string

When i use this function it removes the last letter from the string. It should only replace linebreaks with
tags. What is wrong?

    return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, breakTag);

Upvotes: 1

Views: 205

Answers (2)

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123377

try this instead

 return str.replace(/(\r\n|\n|\r)*$/, breakTag)

(I've used the $ to match the end of the string)

Upvotes: 0

Pointy
Pointy

Reputation: 413720

The first part of your pattern matches any single character that's not > or carriage-return or line feed, but it doesn't add that back to the result string. Thus it always eats the last character before the line break.

Try:

return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, "$1" + breakTag);

Upvotes: 1

Related Questions