Reputation: 11
It's conventional to have spaces before punctuation symbols in French.
I've got texts like this:
Paul m'a dit « Bonjour ! »
I'd like a jquery/javascript function to replace regular spaces with non-breaking spaces before the following characters:
! : ? … ; »
and after this character:
«
Could anyone point me in the right direction? Thank you in advance.
Upvotes: 1
Views: 1534
Reputation: 274
My Typescript helper function with the narrow no-break space code (https://en.wikipedia.org/wiki/Non-breaking_space#Width_variation):
export function replaceNonBreaking(text: string): string {
if (!text) { return text; }
return text.replace(/ (!|:|\?|…|;|»)/g, ' $1').replace('« ', '« ');
}
Upvotes: 0
Reputation: 1709
Like this (EDIT: Tested, works)
function replaceNonBreaking(text) {
return text.replace(/ (!|:|\?|…|;|»)/g, " $1").replace('« ', '« ');
}
Replacing all occurrences of "[space][special-char]" to "[non-breaking space][that special-char]" in the string.
Upvotes: 2
Reputation: 63514
There's probably a far better regex way than this one (regex is my downfall), but this one works:
str = str.replace(/\s([!:\?…;»])/g, function (el1, el2) {
return ' ' + el2;
}).replace(/(«)\s/g, function (el1, el2) {
return el2 + ' ';
});
Upvotes: 1
Reputation: 2206
You can do something like :
var str = 'Paul m\'a dit : « Bonjour ! »';
var corrected_str = str.replace(/ (!|\:|\?|…|;|»)/g, ' $1', str).replace('« ', '« ');
(I think you should add a non-breaking space before « too.)
Upvotes: 0