1

I am working on a text justify function in JavaScript and i'd like to use a regex snippet that worked for my previous Ruby justify function.

The regex is as follows:

/(?<=\s|\A).{1,#{length}}(?=\s|\z)/

I'm using this as a template to extract a line of text that's within a specified length variable from a larger string that doesn't have line-returns. The regex ensures that I am capturing all complete words and requisite whitespace within this length and not cutting any words off.

I'd like to create a JavaScript analogue of this regex.

I've tried the basic replace of syntax between Ruby and JS, as follows:

^\s|\A.{1,length}\s|\z$

with no success. Any help would be greatly appreciated.

2
  • github.com/VerbalExpressions/JSVerbalExpressions might be useful Commented Jan 20, 2016 at 23:17
  • 3
    Lookbehind is not supported and you got it right that you removed it. Now, the anchors \A and \z are not supported either. You will need to use a constructor notation to declare a dynamic pattern as variable interpolation does not work as in Ruby. Use something like var length = 5; var rx = RegExp("(?:\\s|^)(.{1, " + length + "})(?=\\s|$)", "g"); - your value will be in Group 1 (you will need to run RegExp#exec in a while loop). Commented Jan 20, 2016 at 23:19

1 Answer 1

1

Lookbehind is not supported and you got it right that you removed it. Now, the anchors \A and \z are not supported either. You will need to use a constructor notation to declare a dynamic pattern as variable interpolation does not work as in Ruby.

Use something like

var length = 5; 
var re = RegExp("(?:\\s|^)(.{1," + length + "})(?=\\s|$)", "g");
var str = 'My cool code on StackOverflow.';
var res = [];
while ((m = re.exec(str)) !== null) {
  res.push(m[1]);            // Your value is in Group 1
}
document.body.innerHTML = "<pre>" + JSON.stringify(res, 0, 4) + "</pre>"; // just demo

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

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.