0

I submitted this Extract String RegEx Question post not too long ago.
I want to enhance the expression pattern more.

So far this works nicely:

<script> 
  // extract the inc/funcs.asp from the variable.
  var text = '<!-- #include file="inc/funcs.asp" -->'; 
  var pattern = /file="([^"]+)/i
  var result = (text.match(pattern) || ['', ''])[1]; 
  console.log(result); // returns: inc/funcs.asp
</script>

I'm now testing white-space nuances. The pattern I'm applying is: /file="([^"]+)/i I'd like to add more to this pattern.

For example:

var pattern = /#include file="([^"]+)/i

And this works, unless there's more space between the #include and file.

So I altered the pattern to this:

var pattern = /#include(\s+)file="([^"]+)/i

Full Script:

<script>
  var text = '<!-- #Include      File="inc/funcs.asp" -->'; 
  var pattern = /#include(\s+)file="([^"]+)/i 
  var result = (text.match(pattern) || ['', ''])[1]; 
  var count = result.length; 

  if(count > 0){ 
    console.log(result); 
  }
</script>

The count variable is greater than 0, and runs the console.log. But the variable result is empty.

What I'm missing?

2 Answers 2

1

Remove the capturing group - () of \s+ from regex. Otherwise, it'll always return spaces in result array.

var pattern = /#include\s+file="([^"]+)/i;

Demo

var text = '<!-- #Include      File="inc/funcs.asp" -->';
var pattern = /#include\s+file="([^"]+)/i;
var result = (text.match(pattern) || ['', ''])[1];

if (result.length > 0) {
  alert(result);
}

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

1 Comment

That was it! I will need to understand capturing groups more now.
0

That's because you added a group, and the element at index 1 in the array returned by match is this group (full of spaces).

Change

var pattern = /#include(\s+)file="([^"]+)/i

to

var pattern = /#include\s+file="([^"]+)/i

An alternative would have been to use a non remembered group ((?:\s+)) but you don't need a group at all.

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.