0

Hello I'm new to Javascript and I'm trying to figure out how to extract a substring from another string.

I know the substring() method captures the string from a starting index to an ending.

But in my case I want to capture a string that starts after "val=" all the way to the end of the super-string.

Ideas?

Thanks

Jonathan
  • 8,771
  • 4
  • 41
  • 78
Kingamere
  • 9,496
  • 23
  • 71
  • 110

4 Answers4

2

You can either use indexOf:

var text = "something val=hello";
var result = text.substr(text.indexOf("val=") + 4);
alert(result);

Or use a regex like your tags suggest:

var text = "something val=hello";
var result = /\bval=(.+)/.exec(text)[1];
alert(result);

Of course, in both cases you should take care of error cases (for instance, what should happen when val= is not in the string).

Lucas Trzesniewski
  • 50,214
  • 11
  • 107
  • 158
1
var str = "val=hello world";
var idx = str.lastIndexOf('=');
var result = str.substring(idx + 1);
silverfighter
  • 6,762
  • 10
  • 46
  • 73
1

Your best bet would probably be to read this first: https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem

Then proceed to this: How can I get query string values in JavaScript?

Community
  • 1
  • 1
Jonathan
  • 8,771
  • 4
  • 41
  • 78
1

You can use either substr / substring:

var identifier = "val=";
var text = "your text val=foo";

var value = text.substring(text.indexOf(identifier) + identifier.length);

Or regular expression, for example using the string's method match:

var text = "your text val=foo";
var matches = text.match(/val=([\s\S]*)/);
var value = matches && matches[1];
ZER0
  • 24,846
  • 5
  • 51
  • 54