Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS String: Add whitespace between numbers and letters

i need a regular expression or any other method to add whitespaces between numbers and letters in a string.

Example:

"E2356" => "E 2356"
"E123-F456" => "E 123-F 456"

I already found a regular expression capable of it but it is not possible with Javascript:

(?<=[^0-9])(?=[0-9])

Thanks!

like image 645
Arjuna Wenzel Avatar asked Nov 16 '25 05:11

Arjuna Wenzel


1 Answers

Instead of a look-behind, just match the non-digit:

[^0-9](?=[0-9])

And replace with "$& ".

The [^0-9] subpattern will match 1 character that is not a digit that can be referenced with $& (the whole matched text) in the replacement pattern. (?=[0-9]) lookahead will make sure there is a digit right after it.

See demo

var re = /[^0-9](?=[0-9])/g; 
var str = 'E2356<br/>E123-F456';
var result = str.replace(re, '$& ');
document.write(result);
like image 195
Wiktor Stribiżew Avatar answered Nov 18 '25 21:11

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!