-1

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
  • 4
    are u sure it not working ?? its works Commented Jan 14, 2018 at 9:20
  • 3
    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. Commented Jan 14, 2018 at 9:23
  • try console.log(feeling.replace(/{{.*}}/, 'happy !')) . @user2864740 says. Commented Jan 14, 2018 at 9:24
  • I keep falling into this pit as well. Commented Jan 14, 2018 at 9:31

2 Answers 2

1

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);

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

Comments

0

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)

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.