I'm having trouble with a replace method in JavaScript. The application crashes when a value is null. What is the best way around this issue?
datafield.putValue(value.replace("~","&"));
update
all that was need was a simple if statement wrapped around.
if(value != null)
{
datafield.putValue(value.replace("~","&"));
}
I'm having trouble with a replace method in JavaScript. The application crashes when a value is null. What is the best way around this issue?
datafield.putValue(value.replace("~","&"));
update
all that was need was a simple if statement wrapped around.
if(value != null)
{
datafield.putValue(value.replace("~","&"));
}
Share
Improve this question
edited Jun 9, 2017 at 12:12
Bish25
asked Jun 9, 2016 at 11:54
Bish25Bish25
6161 gold badge11 silver badges37 bronze badges
11
- 1 use ternary operator – Siva Kumar Commented Jun 9, 2016 at 11:55
-
2
Are you sure that's Java? Doesn't look like Java.
Replace
is capitalized and it has a JavaScript-style literal regular expression. The former suggests it's C#; the latter suggests it's JavaScript. – T.J. Crowder Commented Jun 9, 2016 at 11:58 - 1 This is still not valid Java ... – Tom Commented Jun 9, 2016 at 12:00
- 1 Still has the JavaScript-style regular expression. – T.J. Crowder Commented Jun 9, 2016 at 12:00
-
1
@tak3shi: No, that would try to replace the literal string
/~/g
with&
. Sam, I've fixed the question with valid Java code to do a replace of~
with&
, globally in the string. You could also use.replace('~', '&'
)` (thechar
-based one instead of theCharSequence
-based one) since both the search text and the replacement are exactly one character long. – T.J. Crowder Commented Jun 9, 2016 at 12:22
1 Answer
Reset to default 4You could use if
, certainly, either to not put anything or to put null
:
if (Value != null) {
datafield.putValue(Value.replace("~","&"));
}
or
if (Value != null) {
datafield.putValue(Value.replace("~","&"));
} else {
datafield.putValue(null);
}
...but if you want to do that last one I'd use the conditional operator:
datafield.putValue(Value == null ? null : Value.replace("~","&"));
...or is replace clever enough to not check when null...
if Value
is null
, replace
will never get called (in Java). So it's impossible for replace
to be "clever" enough to handle it.
Side note: Since both the search text and the replacement are exactly one character long, you could use the char
-based version of replace
instead of the CharSequence
-based one: Value.replace('~', '&')
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745271812a4619792.html
评论列表(0条)