Je veux formater la chaîne en JavaScript. Avec formatage, je veux dire:
Je sais que je peux y parvenir avec regex code>, mais ne pouvait pas comprendre comment. p>
Maintenant: P> Hello, how areyou?
5 Réponses :
J'ai résolu votre problème avec 3 expressions régulières, mais la première est réalisée par le p> string.trim () existant.trim () code> méthode de javascript.
var myString = " Hello , how are you ? ";
myString = myString
.trim() // trim start and end
.replace(/[ \t\n]+/g, ' ') // reduce whitespace to one space
.replace(/ ([,\?\.\!\;])/g, '$1'); // remove one space before pointation characters
console.log(myString);
<div id='test'></div>
PRO-CONSEIL: B> N'utilisez jamais innerhtml code> pour les supports non-HTML et non évalués texte. Utilisez
Innertext code>
à la place.
Un autre conseil: Utilisez @
Une autre façon d'aller avec une seule regex:
p>
var myString = " Hello , how are you ? "; myString = myString.replace(/^\s+|\s+$|\s+(?![a-z])/g, ''); console.log(myString);
Vous pouvez produire la chaîne souhaitée en remplaçant les allumettes de l'expression régulière suivante avec des chaînes vides.
^ : match beginning of string [ \t]* : match 0+ spaces or tabs | : or [ \t] : match a space or tab (?=[ \t,?]) : next character must be a space, tab, comma or question mark | : or [ \t]* : match 0+ spaces or tabs $ : match end of string
J'utilise une fois remplacé pour faire cela.
myString.replace(/(^\s+|\s+$)/g, ""); //same as myString.trim(); myString.replace((\s+(?=[\.,!?])), ""); //Will only matches spaces (which following .,!?) //So only spaces will be replace myString.replace((\s+(?=\s)), ""); //same as with following ,.!? But this case with space //see on the regex replaced with same that is "", so we can combine them together myString.replace(/(\s+(?=[,\.?!])|^\s+|\s+$|\s+(?=\s))/g, "")
Il suffit d'utiliser la garniture () au lieu de regex comme ici W3Schools.com/jsref/jsref_trim_string.asp //a >