1

This may be the silliest question I'm asking But I already wasted nearly 30 mins to get this done and thought to ask from you guys.

What basically this code needs to do is just replace the str value if it's in the list (Only if whole str matched with the key), otherwise, return the str. However, I'm getting undefined if it wasn't on the list.

NOTE: I don't want it to wrap the result inside an if/else statement and if undefined return the str. Any way to do it with a simple tweak?

var list = {
    'a': 'aaa',
    'b': 'bbb',
    'aa': 'ccc',
    'bb': 'ddd',
}

var str = 'a'

var newStr = str.replace(new RegExp(str), (a) => list[a])

// This is how it should be if it wasn't a 'var'. But with a `var` ?
// var newStr = str.replace(new RegExp(/str/), (a) => list[a]) 

console.log(newStr)
6
  • Any reason to require regex? Or replacement? Commented Jun 4, 2021 at 16:25
  • Just a replacement is sufficient. Commented Jun 4, 2021 at 16:26
  • 4
    I'd say newStr = list[str] ?? str is all you need. That's why I wonder about the replacement. Commented Jun 4, 2021 at 16:26
  • 1
    @VLAZ you mean || right? Commented Jun 4, 2021 at 16:27
  • 1
    @ilkerkaran if the replacement is "" you'd get back str and I don't think it's intended. Commented Jun 4, 2021 at 16:28

2 Answers 2

2

As pointed by @VLAZ the answer is just...

newStr = list[str] || str

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

1 Comment

I said ?? but you can use || if you're OK with it.
1

Use the "Nullish coalescing operator (??)":

The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.

This can be contrasted with the logical OR (||) operator, which returns the right-hand side operand if the left operand is any falsy value, not only null or undefined. In other words, if you use || to provide some default value to another variable foo, you may encounter unexpected behaviors if you consider some falsy values as usable (e.g., '' or 0).

var list = {
    'a': 'aaa',
    'b': 'bbb',
    'aa': 'ccc',
    'bb': 'ddd',
}
var str = 'a'
var newStr = list[str] ?? str;
console.log(newStr)

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.