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!
2 Answers 2
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);
Comments
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)
replacefunction as it does not modify the string:console.log(feeling.replace(/{{.*}}/, 'happy !'))will show the desired output.