Home > OS >  Javascript expression to replace one value with another without repeating the value
Javascript expression to replace one value with another without repeating the value

Time:02-04

Is there a shorthand way to replace a value with a different value in javascript?

Here's the most concise way I know of yet:

getAttr(data,"PARTITIONING_SCHEME") === "[None]" ? "" : getAttr(data,"PARTITIONING_SCHEME") 

But that requires repeating myself, and in this case calling the getAttr function twice to get the same value. Obviously I can assign it to a variable once and then do the conditional logic, but that'd be another line of code and I'm looking for conciseness.

I suppose I could do a string replacement:

getAttr(data,"PARTITIONING_SCHEME").replace("[None]","")

But that would wrongly modify some longer string that happens to have [None] embedded in it. I'm sure regexp could do it but I'd prefer not to have frequent recourse to regexp... just need something quick, concise and easy to remember. Seems simple enough.

This is not asking about the javascript ternary operator ? which is what I showed above and requires repeating the operand on both sides, nor nullish coallescing ?? or || which only replace nullish values. I want to replace one non-nullish value with another, otherwise leave it alone.

I can do this of course by extending the String prototype:

  String.prototype.swap = function(o,n) {
    return this === o ? n : this
  }

And then anywhere in my app:

 getAttr(data,"PARTITIONING_SCHEME").swap("[None]","")

But wanted to check to see if there isn't something built-in first?

CodePudding user response:

What about:

getAttr(data,"PARTITIONING_SCHEME").replace(/^\[None\]$/,"")

It will replace [None] only, when it is the only content of the string.

Or create a little utility function:

const noneBlank=s=>s=="[None]"?"":s;

// apply it here:
noneBlank(getAttr(data,"PARTITIONING_SCHEME"))

CodePudding user response:

There is no reference type in javascript, therefore it is not possible to use

attr.someFunc()

or

someFunc(attr)

to assign attr to something else. A variable or attribute binding can only be changed via an assignment.

Surely you can use functions to change the content of the variable, but only when it is mutable. Therefore your imaginary String.swap is not possible either.

A realistic way to solve the problem at hand would be to have setAttr along with getAttr, to which you can pass a mutator function:

setAttr(data,"PARTITIONING_SCHEME", x => x === '[None]' ? '' : x) 
  • Related