1

I am trying to extract a string value, but I need a generic code to extract the values.

INPUT 1 : "/rack=1/shelf=1/slot=12/port=200"
INPUT 2 : "/shelf=1/slot=13/port=3"
INPUT 3 : "/shelf=1/slot=142/subslot=2/port=4"

I need the below output:

OUTPUT 1 : "/rack=1/shelf=1/slot=12"
OUTPUT 2 : "/shelf=1/slot=13"
OUTPUT 3 : "/shelf=1/slot=142"

Basically I am trying to extract up to the slot value. I tried indexOf and substr, but those are specific to individual string values. I require a generic code to extract up to slot. Is there a way how I can match the numeric after the slot and perform extraction?

2
  • Should OUTPUT 1 be "/rack=1/shelf=1/slot=12"? And the keyword you are looking for is regex. Commented Aug 19, 2021 at 7:37
  • 1
    Yes. i updated the output with "/rack=1/shelf=1/slot=12" Commented Aug 19, 2021 at 7:46

3 Answers 3

1

We can try matching on the following regular expression, which captures all content we want to appear in the output:

^(.*\/shelf=\d+\/slot=\d+).*$

Note that this greedily captures all content up to, and including, the /shelf followed by /slot portions of the input path.

var inputs = ["/rack=1/shelf=1/slot=12/port=200", "/shelf=1/slot=13/port=3", "/shelf=1/slot=142/subslot=2/port=4"];
for (var i=0; i < inputs.length; ++i) {
    var output = inputs[i].replace(/^(.*\/shelf=\d+\/slot=\d+).*$/, "$1");
    console.log(inputs[i] + " => " + output);
}

Sign up to request clarification or add additional context in comments.

Comments

0

If it will always be the last substring, you could use slice:

function removeLastSubStr(str, delimiter) {
  const splitStr = str.split(delimiter);

  return splitStr
    .slice(0, splitStr.length - 1)
    .join(delimiter);
}

const str = "/rack=1/shelf=1/slot=12/port=200";

console.log(
  removeLastSubStr(str, '/')
)

if you don't know where your substring is, but you know what it is you could filter it out of the split array:


function removeSubStr(str, delimiter, substr) {
  const splitStr = str.split(delimiter);

  return splitStr
    .filter(s => !s.contains(substr))
    .join(delimiter);
}

const str = "/rack=1/shelf=1/slot=12/port=200";

console.log(
  removeSubStr(str, '/', 'port=200')
)

console.log(
  removeSubStr(str, '/', 'port')
)

Comments

0

You could use this function. If "subslot" is always after "slot" then you can remove the "/" in indexOf("/slot")

function exractUptoSlot(str) {
    return str.substring(0,str.indexOf("/",str.indexOf("/slot")));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.