Samantha J T Star
Samantha J T Star

Reputation: 32828

How can I combine checking if a string exists with the ? operator?

My server name can be one of these:

var baseUrl = "http://localhost:3048"
var baseUrl = "http://www.example.org"
var baseUrl = "https://secure.example.org:443"

I want the variable server to equal "" if the baseUrl does not contain the word localhost and to equal "localhost" if it contains that word.

Is there a way I can do this with a single line of code?

Upvotes: 0

Views: 24

Answers (2)

Sudhansu Choudhary
Sudhansu Choudhary

Reputation: 3360

This would work too, but not sure about browser compatibility for .includes() method,

var host = baseUrl.includes('localhost')? 'localhost' : '';

Upvotes: 1

AmmarCSE
AmmarCSE

Reputation: 30607

Use the ternary operator and indexOf()

var server = baseUrl.indexOf('localhost') > -1 ? 'localhost' : '';

Upvotes: 3

Related Questions