Reputation: 175
How to insert space between a number and string / character
I have a regex question.
How do I insert a space between a numeric character and a letter.
For example:
var sentence = "It contains 37mg of salt"
I want the output to be:
It contains 37 mg of salt.
Upvotes: 0
Views: 64
Reputation: 36564
You can match the number using (\d+)
and add a white space in the replaced string in front of the matched number
var sentence = "It contains 37mg of salt"
let res = sentence.replace(/(\d+)/g,"$1 ")
console.log(res)
Upvotes: 2
Reputation: 4097
Match a number, lookahead for a letter, then replace with the number with a space after it:
var sentence = "It contains 37mg of salt";
const result = sentence.replace(/\d(?=[a-z])/i, '$& ');
console.log(result);
Upvotes: 4