Home > Blockchain >  How insert space before certain data?
How insert space before certain data?

Time:07-13

I have next type of string

const string = 'some text some text in44 some text'

How I can transform it to next, with regexp / js code

const string = 'some text some text in 44 some text'

So, I just need insert space before every number value in string that comes after in. Does it possible to implement?

CodePudding user response:

You can use a regex combined with the method replaceAll to do what you require easily, for example you can use a regex as follow:

// Match all the numbers composed by at least 1 digit, preceded by at least 1 character
const regex = /([a-zA-Z] )(\d )/g;
let string = 'some text some text in44 some text'
// Replace all the match as "First group" (the characters matched by the '[a-zA-Z] ')   space   "Second group" (the digits matched by the \d )
string = string.replaceAll(regex, '$1 $2');
  • Related