Reputation: 152
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!
Upvotes: 2
Views: 7056
Reputation: 626689
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);
Upvotes: 9
Reputation: 560
You cannot format a string using regex. Regex helps you validate that whether a certain string follow the language described by expression.
Regex helps you capture certain parts of the string in different variables and then format them as you want to get the desired output.
So I would suggest you do something like this :
var data = "E2304" ;
var regex = ([^0-9])([0-9]*)/g ;
data.replace(/regex, '$1 $2') ;
Upvotes: 0
Reputation:
Match the two-character sequence of letter followed by number, with capture groups for both the letter and number, then use String#replace
with the $1
and $2
placeholders to refer to the content of the capture groups, with a space in between.
str.replace(/([^0-9])([0-9])/g, '$1 $2')
^^$1^^ ^^$2^
The g
flag ensures all occurrences are replaced, of course.
Upvotes: 5
Reputation: 3200
Try below code
var test = "E123-F456".match(/[a-zA-Z]+|[0-9]+/g);
console.log(test.join(' '));
fiddle http://jsfiddle.net/anandgh/h2g8cnha/
Upvotes: -1
Reputation: 101473
Use String#replace
:
'E123-F456'.replace(/([A-Z])(\d)/g, '$1 $2')
// >>> "E 123-F 456"
$1
and $2
are the captured groups from the regex and are separated by a space. The expression assumes you only have uppercase characters. Remember to add the g
flag to your expression to replace every occurrence.
Upvotes: 1