Reputation: 189
I have to insert a space after every two characters in a string but by completely ignoring the newline character. I am able to do the spacing part but the problem comes with the newline as that is also counted as a character and when rendering the string it adds space at wrong positions.
let str = '23456\n734526754'
console.log(str)
str = str.match(/.{2}/g).join(' ');
console.log(str)
For the above code the output comes as
23 45 67
3 45 26 75 3
What should be the ideal output is
23 45 67
34 52 67 53
How can I ignore the newline character completely?
Upvotes: 2
Views: 675
Reputation: 2165
You need to update your code.
let str = '234562\n7345267542';
str = str.replace(/(.{2})/g, "$1 ").trim();
console.log(str);
Solution details :
1. expression .{2} matches two characters
2. $1 is for adding space after each group of 2 character
3. g is for match all values
4. trim method removes any leading and trailing whitespace from string
Upvotes: 2
Reputation: 785641
You may use this spacer function in Javascript:
function spacer(s) {
return s
.replace(/^((?:.{2})*.)\n(.)(.*)/g, '$1$2\n$3')
.replace(/.{2}(?=.)/g, '$& ');
}
console.log(spacer('23456\n734526754'));
//=> '23 45 67\n34 52 67 54'
console.log(spacer('234562\n7345267542'));
//=> '23 45 62\n73 45 26 75 42'
Solution Details:
spacer
function user 2 .replace
invocations.replace
finds \n
after matching odd number of characters and moves it one position ahead using 3 capture groups.replace
matches a pair of any characters (except line break) and inserts a space after the matchUpvotes: 1
Reputation: 522211
Here is an approach using a single regex replacement:
var str = '23456\n734526754';
var output = str.replace(/(\S{1,2})(?=\S)/g, "$1 ");
console.log(output);
The regex pattern used here says to match:
(\S{1,2})
match AND capture either 1 or 2 non whitespace characters(?=\S)
assert that non whitespace follows (do not add space after final group)Then, we replace with $1
to effectively add a space after each group.
Upvotes: 0