0

I know that you can use ${} inside a string to put a var but here it seems it doesn't want to recognise the var and it is not in the brackets

var str = s.toLowerCase();
        var counts = {};
        var ch, index, len, count;

        for (index = 0, len = str.length; index < len; ++index) {
            ch = str.charAt(index);
            count = counts[ch];
            counts[ch] = count ? count + 1 : 1;
        }
        for (ch in counts) {
            console.log('${ch}(${counts[ch]})');
        }   
2
  • Are you sure something like this exists without defining an extra function to handle this? Commented Jul 29, 2017 at 17:55
  • 1
    It's typo , replace ' with ` Commented Jul 29, 2017 at 17:58

3 Answers 3

2

ES2015 template literals require a back tick:

console.log(`${ch}(${counts[ch]})`);

Working example:

const s = 'An example string with some duplicate characters.';

var str = s.toLowerCase();
var counts = {};
var ch, index, len, count;

for (index = 0, len = str.length; index < len; ++index) {
  ch = str.charAt(index);
  count = counts[ch];
  counts[ch] = count ? count + 1 : 1;
}
for (ch in counts) {
  console.log(`${ch}(${counts[ch]})`);
} 

Sign up to request clarification or add additional context in comments.

4 Comments

the problem is not in the brackets
What do you mean? Where is it, then?
i want to be inside 1 string
There's only one string literal. Could you please clarify what the result should look like?
1

You need to use the back tick. Use ` instead of '.

Comments

1

You need to put your string inside ``, not ''.

var myVar = 'hello world!';
console.log(`${myVar}`);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.