JS comparing strings with line breaks - javascript

I'm trying to compare 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 comparing 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 completely 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 compares 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');

My first thought is to remove all non alpha characters from both strings and compare 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');

Related

Shifting characters in a string

I am trying to develop a function inside an external Javascript file that I can later call/use inside an HTML file. I need this function to take a string and shift the individual characters over one, I.E the string "ABCDE" would become "BCDEA" after going through the function. But instead of that specific string, I would like to be able to use a string variable named "key", since the string that needs to be shifted can be whatever the user enters for it. I am completely lost and unsure of what to do so any help would be appreciated.
The only thing I can think of possibly doing is subtracting the index of the first character in the string by one, so it would be -1 resulting in the code thinking that it is at the back of the string since the last character is assigned -1 but I don't know if it will even work, or how to set it up if it did.
You can shift a string using the following function that uses simple substring() manipulation which is a function you can call on all strings:
function shiftString(str, shift) {
return str.substring(shift) + str.substring(0, shift);
}
Running for instance shiftString("ABCDE", 2) will result in "CDEAB", since:
str.substring(2) == "CDE" (take all characters from the second index onward; strings are zero-indexed)
str.substring(0, 2) == "AB" (take the 0-th index until the second index)

Having trouble with Javascript basic excecution

HELP!! I am new to Java and have been stranded on this problem for the past hour and a half
Use String class methods to manipulate these
strings as follows.
Use the tab escape character to line-up the outputs after the labels as
follows
a) proper label . . .: Output value
b) proper label . . .: Output value
c) proper label . . .: Output value
d) proper label . . .: Output value
Determine the length of string_1.
Determine the length of string_2.
Concatenate both strings.
Check if the two strings have same set of characters with regard to case (i.e., equal).
Convert string_1 to upper case.
Convert string_2 to lower case.
Extract a valid sub-string of multiple characters from string_1.
You must additionally practice how to ask questions and use Stack Overflow, but without spoonfeeding you. You can find everything you need here:
You can calculate the length of a string using:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length
You can concatenate using the + symbol between two strings.
You can check if two strings are the "same set of characters" aka are exactly identical by comparing them together, (hint: = and an if statement, but do you want to use only one = ?). If they are equivalent, return what?
JavaScript has built in string manipulation methods as well that you could investigate:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase
You can also investigate a string prototype known as substring:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring

Remove value from name-value pair string in JavaScript

I have a JavaScript string like dog=1,cat=2,horse=3. The names and values can be anything. I want to remove dog and whatever value is associated with it from the string. So in this example I would end up with cat=2,horse=3. There may not be a entry for dog in the string, and it could be anywhere within the string, e.g. cat=22,dog=17,horse=3 which would end up as cat=22,horse=3.
The names and values will just be alphanumeric with no special characters like quotes and equals signs within them.
What is the best way of going about this in JavaScript?
Simplest solution:
str.split(",").filter(function(kv) {
return kv.slice(0, 4) != "dog=";
}.join(",")
You can do some regex magic as well, but that's not going to be as clear (and maintainable):
str.replace(.replace(/(,|^)dog=[^,]*/g, "").replace(/^,/,"")
You could do this, although may not be the best way:
convert the string to array as it is comma seperated.
remove the dog from the array.
join the array back as a string.

What does .split() return if the string has no match?

In this JavaScript code if the variable data does not have that character . then what will split return?
x = data.split('.');
Will it be an array of the original string?
Yes, as per ECMA262 15.5.4.14 String.prototype.split (separator, limit), if the separator is not in the string, it returns a one-element array with the original string in it. The outcome can be inferred from:
Returns an Array object into which substrings of the result of converting this object to a String have been stored. The substrings are determined by searching from left to right for occurrences of separator; these occurrences are not part of any substring in the returned array, but serve to divide up the String value.
If you're not happy inferring that, you can follow the rather voluminous steps at the bottom and you'll see that's what it does.
Testing it, if you type in the code:
alert('paxdiablo'.split('.')[0]);
you'll see that it outputs paxdiablo, the first (and only) array element. Running:
alert('pax.diablo'.split('.')[0]);
alert('pax.diablo'.split('.')[1]);
on the other hand will give you two alerts, one for pax and one for diablo.
.split() will return an array. However,
The value you are splitting needs to be a string.
If the value you are splitting doesn't contain the separator, and the value ends up being an integer (or something other than a string) the call to .split() will throw an error:
Uncaught TypeError: values.split is not a function.
For example, if you are loading in a comma-separated list of ID's, and the record has only has one ID (ex. 42), and you attempt to split that list of ID's, you will get the above error since the value you are splitting is considered an int; not a string.
You may want to preface the value you are splitting with .toString():
aValueToSplit.toString().split('.');

How do I get the javascript split function to extract null values from a delimited string

I'm trying to parse a delimited string using the javascript split function. I'm using a double character delimiter.
So for e.g. if the string contains employee related data with the following fields:
Emp Id (mandatory)
Name (mandatory)
Age (optional)
Mobile No (optional)
and the delimiter used is |* (i.e. pipe followed by star)
I may have data like this
5322|*Mike|*21|*077665543
5323|*Jen|*|*077665543
5324|*Raj|*25|*
5325|*Alan|*|*
How do I extract null values into the array returned by split?
If I use Record.split(/\|\*/) It seems to ignore the null values. Do I need to use other functions like regex exec + substring to do this? The split function seems to be quite convenient except for this issue.
What you're doing is correct, and the null values are present.
>>> "5325|*Alan|*|*".split(/\|\*/)
["5325", "Alan", "", ""]
Do not confuse null with an empty string. Your regular expression splits the delimited string properly, capturing empty strings when the fields are "empty" as they should. If you need these array elements to be null, then you'd have to post-process the returned array yourself.

Categories

Resources