2

I have a question on how to search for a substring using Regexp.

Say, I have a "base" string, such as:
image height=X width=Y end

Both height and width in the above "base" string are assigned integer values that vary, i.e.:
image height=15 width=20 end
image height=10 width=10 end
image height=20 width=5 end

So my question is whether it's possible to fetch width value using canonical regex given that the first part of the substring effectively changes?

2
  • 2
    given that the first part of the substring effectively changes <- could you explain what you mean by that? Commented Sep 30, 2015 at 19:34
  • I'm not sure about the purpose. What are you trying to do with it? Commented Sep 30, 2015 at 19:36

2 Answers 2

5

This regexp /width=(\d+)/ should do it:

var strs = ['image height=15 width=20 end this is another width=123', 'width=200 and image height=10 width=10 end', 'image height=20 width=5 end'];

var widths = strs.map(function(str) {
   var matches = str.match(/\bimage height=\d+ width=(\d+) end\b/);
   return matches && matches.length > 1 ? parseInt(matches[1], 10) : null;
});

document.write(widths);

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

3 Comments

You should put \b before width, so it doesn't match something like contentwidth=123
Thanks, but is there a way to actually have this follow the exact "base" string format? Assuming "width" is present elsewhere in the source text, this would return all such values, whereas I only need those between the "image height=15 width=" and "end".
Indeed - see edit. I've added to the example strings width=* before and after respectively.
0

The answer by Ori Drori is correct if you don't require the exact form you specified. If you do, you could use this:

var strs = ['image height=15 width=20 end', 'image height=10 width=10 end', 'image height=20 width=5 end'];

var widths = strs.map(function(str) {
   var matches = str.match(/image\ height=\d+\ width=(\d+)\ end/);

   return matches.length > 1 ? parseInt(matches[1], 10) : null;
});

document.write(widths);

2 Comments

Thanks, but your code returns parameters for "height" and not "width". Can you correct that, please?
@Alex Ah yeah, it actually gets both but I forgot to mention that. I'll fix the answer.

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.