admin管理员组

文章数量:1313121

I'm trying to pare two equal strings: a textarea value (or textContent, or innerHTML) and a string stored as an attribute in Backbone model, e.g. "A string↵with line break". And this paring always returns false.
Comparing length of these strings reveals the difference (the stored one is one symbol longer). The question is how to prepare the first string (extracted from textarea) to make it pletely equal to the second one (stored in model).

P.S. They are both typeof === 'string'.

P.P.S. The main problem is how to make Backbone see the equality while setting an attribute:

this.model.set({ attr: textareaValue }).

Backbone uses Underscore's method which simply pares two strings in this case:

return '' + a === '' + b;

I've applied encodeURIComponent on both strings: the result is Some%0Atext vs Some%0D%0Atext. So the second one has \r character (it's rendered by Handlebars). Should I insert this character before each \n?

P.P.P.S. Yes, this did the trick: textarea.value.replace(/\n/gm, '\r\n');

I'm trying to pare two equal strings: a textarea value (or textContent, or innerHTML) and a string stored as an attribute in Backbone model, e.g. "A string↵with line break". And this paring always returns false.
Comparing length of these strings reveals the difference (the stored one is one symbol longer). The question is how to prepare the first string (extracted from textarea) to make it pletely equal to the second one (stored in model).

P.S. They are both typeof === 'string'.

P.P.S. The main problem is how to make Backbone see the equality while setting an attribute:

this.model.set({ attr: textareaValue }).

Backbone uses Underscore's method which simply pares two strings in this case:

return '' + a === '' + b;

I've applied encodeURIComponent on both strings: the result is Some%0Atext vs Some%0D%0Atext. So the second one has \r character (it's rendered by Handlebars). Should I insert this character before each \n?

P.P.P.S. Yes, this did the trick: textarea.value.replace(/\n/gm, '\r\n');

Share Improve this question edited Oct 26, 2015 at 20:09 Kiryl Anokhin asked Oct 26, 2015 at 19:09 Kiryl AnokhinKiryl Anokhin 4594 silver badges11 bronze badges 1
  • Replace on /\r?\n/g so you don't end up with \r\r\n if the string does have the \r – Paul S. Commented Oct 26, 2015 at 20:12
Add a ment  | 

2 Answers 2

Reset to default 5

My first thought is to remove all non alpha characters from both strings and pare them afterward.

str.replace(/[^a-zA-Z]/g, "");

The problem was in \r character: textarea value rendered by Handlebars was Some\ntext while string stored in model was Some\r\ntext). And this did the trick: textarea.value.replace(/\n/gm, '\r\n');

本文标签: javascriptJS comparing strings with line breaksStack Overflow