stacktesting
stacktesting

Reputation: 115

How to extract certain string characters in Javascript in a generic way?

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?

Upvotes: 1

Views: 506

Answers (3)

Tom
Tom

Reputation: 5677

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")));
}

Upvotes: 0

seedBoot
seedBoot

Reputation: 394

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')
)

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521073

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);
}

Upvotes: 1

Related Questions