coffeemonitor
coffeemonitor

Reputation: 13120

Javascript Regular Expression Whitespace Detection

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?

Upvotes: 0

Views: 48

Answers (2)

Tushar
Tushar

Reputation: 87203

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);
}

Upvotes: 1

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382130

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.

Upvotes: 0

Related Questions