user1234
user1234

Reputation: 3159

How to get separate out characters from within a string

I have a string:

string = "abc_test_dashboard.json";

The value of string could vary like:

"tes.test.dashboard.json"
"jhgwefj-gfjh.widget.json"

The last "dashboard.json" and "widget.json" is static and could be either of them depending on a condition.

Basically I'm trying to identify if its "dashboard" or "widget" from the string.

I want to do stuff based on:

if ("dashboard.json") {//do some stuff}
else { // do something else
}

I also just realized that I may have multiple files with same name, and hence I may end up getting (1), (2) suffixes i.e: "abc_test_dashboard(1).json", "abc_test_dashboard(2).json". is there any way to test these kind of scenarios?

Thanks

Upvotes: 0

Views: 82

Answers (3)

Renato Gama
Renato Gama

Reputation: 16519

You can do it with

if(string.endsWith('dashboard.json')) {

}

if(string.endsWith('widget.json')) {

}

Also you can use regex if you want (in case your target browsers do not support endsWith);

if (/widget\.json$/.test('widget.json')) { 

}

Using regex you can even extract the initial portion of the file;

var widgetInfo = 'asd.widget.json'.match(/^(.*)widget\.json$/)
if (widgetInfo) {
    console.log(widgetInfo[1]) // will print `asd.`
}

// similar code to check for `dashboard.json`

EDIT:

In the case you commented you can use the following regex; /^(.*)widget(\(.+\))?\.json$/. It will match strings in the forms of randomstring.widget.json and randomstring.widget(1).json, but not randomstring.widget().json

Upvotes: 6

CharmedSatyr
CharmedSatyr

Reputation: 46

If you don't mind RegEx, you can use the String match() method as in the below:

function checkStrEnd(str) {
  if (str.match(/dashboard\.json$/)) {
    console.log('Do dashboard stuff');
  } else if (str.match(/widget\.json$/)) {
    console.log('Do widget stuff');
  } else {
    console.log('Do something else');
  }
}

checkStrEnd('tes.test.dashboard.json'); // 'Do dashboard stuff'
checkStrEnd('jhgwefj-gfjh.widget.json'); // 'Do widget stuff'
checkStrEnd('random string'); // 'Do something else'

Upvotes: 2

Get Off My Lawn
Get Off My Lawn

Reputation: 36299

you can use includes to see if the string exists within the string

let arr = ["tes.test.dashboard.json", "jhgwefj-gfjh.widget.json"]

arr.forEach(item => {
  if (item.includes('dashboard.json')) {
    console.log('dasboard')
  } else if (item.includes('widget.json')) {
    console.log('widget')
  }
})

Upvotes: 1

Related Questions