-3

I have the following text: "configuration/entities/details/attributes/FirstName". I want to break it in such a way that, attributes and FirstName should come out separately, preferably as two variables.

How can I achieve this using JavaScript?

Daredevil
  • 1,672
  • 3
  • 18
  • 47
  • 2
    Please share your attempt. – Hassan Imam Oct 25 '18 at 08:30
  • 1
    Really? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split . I seriously cannot believe if you'd searched online for a few moments you would not have found the solution to this straight away. Did you even look? – ADyson Oct 25 '18 at 08:35
  • Possible duplicate of [How do I split a string, breaking at a particular character?](https://stackoverflow.com/questions/96428/how-do-i-split-a-string-breaking-at-a-particular-character) – ADyson Oct 25 '18 at 09:02

2 Answers2

2

If the structure is always the same, with attribute and name at the end, you can do:

let text = "configuration/entities/details/attributes/FirstName"
let arr = text.split("/"); //["configuration",  "entities","details",  "attributes",  "FirstName"]
let reverse_arr = arr.reverse();
let [name,attr] = reverse_arr;

console.log(name, attr)

The split separates by "/", the reverse() well reverses it, then with destructuring, you say that "take the first two and put it in two variables"

It wont matter if there are more or less elements elements if those two are at the end

lois6b
  • 184
  • 3
  • 15
0

you can do such as this:

let targetString="configuration/entities/details/attributes/FirstName";
let splitArray=targetString.split('/');
let attributes=splitArray[splitArray.length-1]
bolt
  • 90
  • 3