skip to Main Content

I have a string like this…
"1.first. 2.second. 3.third"

and I want it to be like this using JavaScript split
["1.first.", "2.second", "3.third"]

I saw C# is like this Regex.Split(txt, "[0-9]+\.");
but I need it in JavaScript, please help

I try using this…

description.split(/([0-9]+)/)

but it turn out to be like this

[
"1", 
". first",
"2",
". second ",
"3",
".third",
"23",
"two three",
"4",
".four"
]

2

Answers


  1. Just split with ' ':

    console.log("1.first. 2.second 3.third".split(' '));

    If you could have trailing or several spaces between words – match words (non white space characters) with S+ in a regex:

    console.log("1.first. 2.second 3.third".match(/S+/g));
    Login or Signup to reply.
  2. For splitting your string into an array, try this snippet of JavaScript code:

    const str = "1.first. 2.second. 3.third";
    const result = str.split(/ (?=d.)/).map(s => s.trim());
    
    console.log(result);

    This will neatly turn your string into [‘1.first.’, ‘2.second.’, ‘3.third’].

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search