-1

I have to split my sentence into many small strings with a maximum of 10 characters per string including the white spaces using Regex and Js.

let S = "Pre demo edit to 21st Century";
let strArr = s.match(/.{1,10}/g);

expected:

["Pre demo ", "edit to", "21st", "Century"]

actual:

["Pre demo e", "dit to 21s", "t Century"]
Matheswaaran
  • 145
  • 2
  • 11

1 Answers1

2

I don't know if you want to get spaces because in the first position of your expected array have one.

let me know if is this that you need.

let s = "Pre demo edit to 21st Century";
let strArr = s.match(/.{1,10}\b/g);
let res = document.getElementById('res')
res.innerHTML = strArr

console.log(strArr)
<div id="res"></div>
Kappys
  • 673
  • 2
  • 7
  • 20
  • Not sure why this is downvoted - seems to do exactly what OP is wanting – Pete Feb 15 '19 at 12:09
  • @Pete I don't know either... I'm waiting if he need without spaces... – Kappys Feb 15 '19 at 12:12
  • @Pete I think you should add `1234567890` to the beginning and see the results. – revo Feb 15 '19 at 12:12
  • @revo still seems to work with that - the only limitation I see is if you have a word that is longer than 10 characters, it gets sliced to 10 characters but as OP hasn't stated what should happen in that scenario I still think this is ok – Pete Feb 15 '19 at 12:14
  • @Pete Still seems to work? I see `123` is missing in results. – revo Feb 15 '19 at 12:15
  • @revo only if you add 2 more characters to that string and that is covered in my second bit to the comment above – Pete Feb 15 '19 at 12:16
  • @Pete Yes and that makes problems. OP never put boundaries on input string. – revo Feb 15 '19 at 12:18