Ekky
Ekky

Reputation: 790

Want to get specific value from string

I have a JavaScript string sentrptg2c#appqueue#sentrptg2c#vwemployees#.

I want to get last string vwemployees through RegExp or from any JavaScript function.

Please suggest a way to do this in JavaScript.

Upvotes: 0

Views: 95

Answers (5)

user554180
user554180

Reputation:

No magic numbers:

var str = "sentrptg2c#appqueue#sentrptg2c#vwemployees#";
var ar = [];
ar = str.split('#');
ar.pop();
var o = ar.pop();
alert(o);

jsfiddle example

Upvotes: 0

CloudyMarble
CloudyMarble

Reputation: 37566

Try something like this:

String.prototype.between = function(prefix, suffix) {
  s = this;
  var i = s.indexOf(prefix);
  if (i >= 0) {
    s = s.substring(i + prefix.length);
  }
  else {
    return '';
  }
  if (suffix) {
    i = s.indexOf(suffix);
    if (i >= 0) {
      s = s.substring(0, i);
    }
    else {
      return '';
    }
  }
  return s;
}

Upvotes: 0

Yevgeny Simkin
Yevgeny Simkin

Reputation: 28349

if you're sure the string will be separated by "#" then you can split on # and take the last entry... I'm stripping off the last #, if it's there, before splitting the string.

var initialString = "sentrptg2c#appqueue#sentrptg2c#vwemployees#"
var parts = initialString.replace(/\#$/,"").split("#"); //this produces an array

if(parts.length > 0){
  var result = parts[parts.length-1];
}

Upvotes: 0

Danny Beckett
Danny Beckett

Reputation: 20838

You can use the split function:

var str = "sentrptg2c#appqueue#sentrptg2c#vwemployees#";
str = str.split("#");
str = str[str.length-2];
alert(str);

// Output: vwemployees

The reason for -2 is because of the trailing #. If there was no trailing #, it would be -1.

Here's a JSFiddle.

Upvotes: 2

Tracker1
Tracker1

Reputation: 19334

var s = "...#value#";
var re = /#([^#]+)#^/;
var answer = re.match(s)[1] || null;

Upvotes: 0

Related Questions