mark
mark

Reputation: 245

How can I add a whitespace before the first letter in a string?

I am trying to add whitespace before the first letter in a string using Regex. For example if I had a string of "0.5g" I would like the string to become "0.5 g".

I have tried to run a regex query that adds a space after a number, but this causes me problems when it has a decimal point between.

My current regex is

'135mg'.replace(/(\d)([^\d\s%])/g, '$1 $2'); // Returns 135 mg as expected
'0.5g'.replace(/(\d)([^\d\s%])/g, '$1 $2'); // Returns 0. 5 g which is wrong as there is a whitespace before 5

Thanks

Upvotes: 2

Views: 295

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626903

Adding a space before the first letter in the string in JavaScript is possible with

console.log( '135mg'.replace(/[a-zA-Z]/, ' $&') );
console.log( '135mg'.replace(/[a-z]/i, ' $&') );
console.log( '135mg'.replace(/([a-z])/i, ' $1') );

See the regex demo.

Note:

  • The regexps have no g flag, so only the first occurrence will get replaced
  • $& in the replacement pattern refers to the whole match, you actually do not need to wrap the whole pattern with a capturing group and use $1, but a lot of people still prefer this variation due to the fact $& is not well-known.

Upvotes: 1

JeffC
JeffC

Reputation: 25611

With the two examples you provided, this works for both

([\d.]*)([mg]+)

It looks for any combo of digits and '.' followed by any combo of 'm' and 'g' and returns

135 mg
0.5 g

The problem is that it could find many things you don't want, e.g.

1.1.1.mm
1.gggmmm

The question is... are there any false positives? You could try it on your samples and let me know and I'll try to adjust.

Upvotes: 0

Related Questions