I am new to javascript and trying to do some advanced string splitting/replacement.

I have researched all over and read the common SO solutions but no luck.

I am trying to convert this string:

var feeling = "my code makes me {{ unhappy }}"

// your magic code here


console.log(feeling) >> "my code makes me happy!" // desired outcome

So i am trying to replace the brackets and words in them, with a new word..

I tried

feeling.replace(/{{.*}}/, 'happy !')

but it's not working.

Thank you!

4 upvote
  flag
are u sure it not working ?? its works – Nozar Safari
3 upvote
  flag
The code needs to use the output of the replace function as it does not modify the string: console.log(feeling.replace(/{{.*}}/, 'happy !')) will show the desired output. – user2864740
upvote
  flag
try console.log(feeling.replace(/{{.*}}/, 'happy !')) . @user2864740 says. – Nozar Safari
upvote
  flag
I keep falling into this pit as well. – connexo

2 Answers 11

As per the doc https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace here, The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. you just need to receive the output in feeling variable,

var feeling = "my code makes me {{ unhappy }}";
    feeling = feeling.replace(/{{.*}}/, 'happy !');
    console.log(feeling);

Works for me. What are you doing differently?

var feeling = "my code makes me {{ unhappy }}";
// Guessing you failed to update "feeling" with the 
// return from .replace() here
feeling = feeling.replace(/{{.*}}/,'happy !');
console.log(feeling)

Not the answer you're looking for? Browse other questions tagged or ask your own question.