2

I need a JavaScript regex to:

  1. Return the first X words in a string, within the first 15 characters.
  2. A word boundary needs to be treated as anything that is not alphanumeric, so any space or special character.
  3. Any trailing spaces or special characters should not be returned in the match.

I currently have the following:

var regex = /(.{1,15})\b/

Which is satisfying 1 & 2, but not 3.

var matches = 'when-winding/order-made'.match(regex);
console.log(matches[1]); // logs 'when-winding/', but I want 'when-winding'

How can I modify this regex to achieve the desired result?

Here's a fiddle with a more comprehensive example: http://jsfiddle.net/jqs9Lnr0/

3 Answers 3

1

Two issues:

  1. Index 0 in the match is the overall match. The first capture group is at index 1:

    console.log(matches[1]);
    
  2. You'll need to list the characters you want, as . will match anything.

Here's an example using \w (any "word" character) and -, but you'll need to adjust the character class (the bit in [...]):

var regex = /([\w-]{1,15})\b/
var matches = 'when-winding/order-made'.match(regex);
snippet.log(matches[1]);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

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

1 Comment

Thanks for your help. I've corrected the typo with the match index. The problem with this approach is that I do want all the special characters... I just don't want them at the end of the string. Also anything I add to the match, such as a hyphen '-' will potentially be returned if it's the 15th character of a string, for example: regex101.com/r/iS6jF6/29
1
^.{1,15}(?=\w\W).

Try this.See demo.

https://regex101.com/r/iS6jF6/28

For shorter string try ^.{1,14}(?=\w\W|\w$)..See demo.

https://regex101.com/r/iL4kF6/3

1 Comment

Thanks for your help. This is really close to what I'm after. The only problem is that it's not handling strings that 15 characters desirably. 'if-shorter' should return 'if-shorter', currently it's only returning 'if'. Any idea how this can be modified to handle the short strings case? regex101.com/r/iL4kF6/2
0

Your capture group is at index 1, not 0.

console.log(matches[1]);

1 Comment

Thanks for your help. That was a mistake in the question, I'll correct. The regex question still stands console.log(matches[1]); also returns 'when-winding/' instead of 'when-winding'.

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.