user1937021
user1937021

Reputation: 10791

add a space between text and numbers in string

How can I add a space between text and numbers in Jquery.

I have the strings in a variable such as:

var month = "June2016";

I want it as "June 2016".

Upvotes: 0

Views: 1013

Answers (3)

Ataur Rahman Munna
Ataur Rahman Munna

Reputation: 3917

Use match method to split the string.

var res = "june2016".match(/[a-zA-Z]+|[0-9]+/g);
console.log(res[0]); // will print month
console.log(res[1]); // will print year
var result = res[0]+" "+res[1];

Checkout the fiddle.

Upvotes: 0

baao
baao

Reputation: 73241

Just match the number and add a space before it in the replacement

var month = "June2016";
console.log(month.replace(/(\d+)/g, " $1"));

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337560

You can use a Regex which inserts a space between an alpha character and a numerical one. Try this:

var month = "June2016".replace(/([a-z])(\d)/gi, '$1 $2');
console.log(month);

Upvotes: 2

Related Questions