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

1
  • regular expression /val=(.*)/ etc. Commented Oct 12, 2015 at 21:25

4 Answers 4

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

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

Comments

1
var str = "val=hello world";
var idx = str.lastIndexOf('=');
var result = str.substring(idx + 1);

Comments

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?

Comments

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];

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.