-4

I'm sure this is a very basic question, but I've look quite a bit for the answer and I can't find it.

All I want to do is to see if an element in an array matches } (i.e., a right brace). But this doesn't work: line === '}'.

I can use line.match(/^\}$/) (which is what I'm doing).

Guess it has something to do with braces being special characters, but if they're in quotes, why would that matter? Why can't I just quote a punctuation mark?

UPDATE: Ugh, I'm sorry, I don't know how this happened. I swear to God I tested it carefully before posting, but now my code works as expected with line == "}", line === "}", line == '}', and line === '}'. The only thing I can say in my slight defense is that I was struggling with multiple issues in the function and I thought this was still an issue. It wasn't. The issues were all elsewhere.

UPDATE 2: Since people were asking, here's the surrounding function. Its purpose was to iterate through an array containing the lines of a JavaScript file, and copy the text of the passed function. The code assumes a function to copy ends whenever '}' is spotted...which is why I was testing for it. I was constantly getting undefined when calling this code, and I actually did get it to work when I switched to the regex. But apparently I fixed the problem at the same time that I tried just using a regex. The lesson is to test conscientiously and try only one thing at a time:

// Return an array containing the text of the input function.
function load_function_text(funShun) {
  // Iterate through the present JS file's text.
  var line_num = 0; // Track line num so you can grab the previous line.
  var current_function = [];
  var copying_lines = false;
  this_file.forEach(function(line) {
    // Start copying when 'function funShun' is spotted. (Start pushing from previous line.)
    if (line.match("function " + funShun)) {
      current_function.push(this_file[line_num - 1]);
      current_function.push(line);
      copying_lines = true;
      line_num += 1;
    // Stop copying and return when '}' is spotted.
    } else if (copying_lines && line === "}") {
      // Add this line.
      current_function.push(line);
      // Stop copying when end of function is reached.
      copying_lines = false;
    } else {
      if (copying_lines) current_function.push(line);
      line_num += 1;
    }
  });
  return current_function;
}

UPDATE 3: It turns out my original issue was actually legit. It was a Windows newline issue, however. In the Ajax handling function that prepared the this_file array I was iterating over, I was splitting the responseText on \n; but the .js file was created in Windows, so its newlines were all \r\n. Ugh!

So that's why my console was reporting that the entire line was }, but in fact, the entire line I was working with was }\r. I was never matching that, so it could be true that line.match(/^}$/) while false that `line === '}'! As a result, a certain condition I wanted to be true was always false, so the script was always copying to the end of the file, instead of stopping at the end of the bit I wanted to copy. (This is the code that pops up when you click on "view".)

As soon as I started splitting on "\r\n", it worked perfectly in Windows. Then I discovered it wasn't working on Heroku, so I figured out how to do it even better: this_file = xhr.responseText.match(/[^\r?\n]+/g);.

Heroku here, repo here. Thanks for your patience.

globewalldesk
  • 544
  • 1
  • 3
  • 18
  • 1
    Looks like you just need to escape it – anomeric Sep 09 '17 at 17:34
  • 6
    Can you show us a more complete example of your code? (See [mcve]) – evolutionxbox Sep 09 '17 at 17:34
  • 3
    @anomeric no need to escape that character within a string. – evolutionxbox Sep 09 '17 at 17:34
  • 2
    For fun and sport, try `line.trim() === "}"` *(but then the regex shouldn't work either)* ? – adeneo Sep 09 '17 at 17:35
  • 3
    Also, can't reproduce -> https://jsfiddle.net/mq58bxth/ – adeneo Sep 09 '17 at 17:36
  • 2
    `line === '}'` works just fine. – melpomene Sep 09 '17 at 17:36
  • 2
    There is a way I can think of that this could be true as described — did you use `new String()` to create the array element? – Semicolon Sep 09 '17 at 17:37
  • 1
    Probably has to do with how you created the string. `var line = new String('}');` and `var line = '}';` are not the same thing and will actually fail the strict equality check `===` because they are different types (object vs string primitive) despite their values being the same. Remember that `===` compares value *and* type. – skyline3000 Sep 09 '17 at 17:49
  • Thanks everyone. I added the surrounding code and explained why I was confused. Mea culpa, I just didn't test my fixes carefully enough. – globewalldesk Sep 09 '17 at 18:54
  • don't ask people to downvote you for asking a bad question; that's just bad form. just remember that this site is a knowledge repository, and try to re-word your question to make it relevant to others in the future. If you *really* can't do that, and think the question has no value, then closing or deleting it if possible would be appropriate. – Claies Sep 09 '17 at 18:57
  • Since when was humility bad form? – globewalldesk Sep 09 '17 at 19:15
  • 1
    Also if i were you i would remove the part about code review as it actually violates the terms of multiple questions in one and can be considered spam i made a edit suggestion and upvoted your post! –  Sep 09 '17 at 19:37
  • Update 3 above finally reveals the real issue. – globewalldesk Sep 10 '17 at 02:30

2 Answers2

0

=== compares the types, so if line is not the same type as '}' it results in false:

line = ['}']

console.log(line === '}')       // false
console.log(line == '}')        // true
console.log(/^\}$/.test(line))  // true

console.log(typeof line)        // object
console.log(typeof '}')         // string
Slai
  • 22,144
  • 5
  • 45
  • 53
0

Have you tried to do this:

line == '}'

Also: Also I tested:

line === '}'

And it worked fine! Read the above comments!

Try this also like in the other answer by Slai?

 line = new String('}')
console.log(line === '}')   // false
console.log(line == '}')    // true 
console.log(/^\}$/.test(line))  // true 

JSFIDDLE DEMO: https://jsfiddle.net/hanstavo/ck443sbn/