Bonjour,
J'ai créé une fonction qui formate un texte de la manière suivante :
La virgule : texte,[espace] texte
Le point-virgule : texte[espace];[espace]texte
Les deux-points : texte[espace]:[espace]texte
Le point : texte.[espace]texte
Les points de suspension : texte.[espace]texte
Le point d'interrogation : texte[espace]?[espace]texte
Le point d'exclamation : texte[espace]![espace]texte
Les guillemets : texte[espace]«[espace]texte[espace]»[espace]texte
Les parenthèses : texte[espace](texte)[espace]texte
Seulement c'est super long selon la chaine à traiter!! il me semble qu'avec des expressions régulières c'est beaucoup plus simple. Mais je n'y pige rien !
Voici le code :
<script>
function FormaterChaine(sChaine){
sPonctPrecedente = "?|;|!|:|(|[|«|»";
sPonctSuivante = "?|,|.|;|!|:|)|]|«|»";
sTabPonctSuivante = sPonctSuivante.split("|");
sTabPonctPrecedente = sPonctPrecedente.split("|");
TexteFormate1 = "";
y = 0;
for (var i=0; i<sTabPonctSuivante.length; i++) {
sPonctSuivante = sTabPonctSuivante[i];
if (y==0){
var sChaine = sChaine + "|";
LnsChaine = sChaine.length;
}else{
var sChaine = TexteFormate1 + "|";
LnsChaine = sChaine.length;
}
if (sChaine.indexOf(sPonctSuivante)!=-1){
for (var k=0; k<LnsChaine;k++){
if (sChaine.substr(k,1)==sPonctSuivante){
if(sChaine.substr(k,2)!= sPonctSuivante + " "){
TexteFormate1 = TexteFormate1 + sPonctSuivante + " ";
y=y+1
}else{
TexteFormate1 = TexteFormate1 + sPonctSuivante;
y=y+1
}}else{
TexteFormate1 = TexteFormate1 + sChaine.substr(k,1);
y=y+1
}}
}
}
sDernChaine = TexteFormate1.split("|");
LnDernChaine = sDernChaine.length;
for (var k=0; k<LnDernChaine;k++){
if (sDernChaine[k]!=""){
TexteFormate1 = sDernChaine[k];
}
}
TexteFormate1 = TexteFormate1.replace(". . .","...");
TexteFormate1 = TexteFormate1.replace(". .",".");
y=0;
TexteFormate2="";
for (var i=0; i<sTabPonctPrecedente.length; i++) {
sPonctPrecedente = sTabPonctPrecedente[i];
if (y==0){
var sChaine = TexteFormate1 + "|";
LnsChaine = sChaine.length;
}else{
var sChaine = TexteFormate2 + "|";
LnsChaine = sChaine.length;
}
if (sChaine.indexOf(sPonctPrecedente)!=-1){
for (var k=0; k<LnsChaine;k++){
if (sChaine.substr(k,1)==sPonctPrecedente){
if(sChaine.substr(k-1,2)!= " " + sPonctPrecedente){
TexteFormate2 = TexteFormate2 + " " + sPonctPrecedente;
y=y+1
}else{
TexteFormate2 = TexteFormate2 + sPonctPrecedente;
y=y+1
}}else{
TexteFormate2 = TexteFormate2 + sChaine.substr(k,1);
y=y+1
}}
}
}
sDernChaine = TexteFormate2.split("|");
LnDernChaine = sDernChaine.length;
for (var k=0; k<LnDernChaine;k++){
if (sDernChaine[k]!=""){
TexteFormate2 = sDernChaine[k];
}
}
return TexteFormate2
}
var sChaine = "Bonjour,je tente de;formater une chaine.Est-ce que c'est facile?N'est-ce pas!«Fabiano:13»[2008]A suivre...(mai 2008)";
document.write("<b>Avant :</b> <font color=green>" + sChaine + "</font><br>")
document.write("<b>Après :</b> <font color=blue>" + FormaterChaine(sChaine) + "</font>")
</script>