2017-06-20 12 views
2

問題は簡単ですが、わかりません。私は単純なフォーム(テキストエリア)をユーザーがテキストを入力し、このテキストがデータベースに保存されます。問題は次のとおりです。テキストを保存する前に不要なスペースを削除したい。だから私は、単純なJavascriptの機能作成:Javascript - 直後に改行が続くスペースを削除する

str.replace(/\n\s*\n\s*\n/g, '\n'); 

をしかし、それはスペースを削除していない場合、ユーザー投稿テキストのように:

hello world  \nanother sample   \n test 

(ユーザが追加したときにスペース/最後の単語の後のスペースとその後、新しい行に別の単語をポスト、これらのスペースは左(ととしてデータベースに保存される):

hello word <br>another sample   <br> test 

など

hello word<br>another sample<br>test 
+0

正規表現はあなたの友達です;) – jdmdevdotnet

+0

それは(私はそれがいえたことを望むではないですが、私を信じて;) – Tom

+0

あなたの正規表現少なくとも3つの改行が含まれている空白の配列のみ一致します。 '\ s * \ n'を使用してください。 – Bergi

答えて

4

ちょうどあなたの正規表現を簡素化する必要があります:私は必要なものは結果があるように、新しい行が続き、これらの空間はJavaScriptによって除去されていることである

const input = 'hello world  \nanother sample   \n test'; 
 
const output = input 
 
    // Remove all whitespace before and after a linebreak 
 
    .replace(/\s*\n\s*/g, '\n'); 
 
console.log(output);

またはデータベースに保存されているように見たい場合:

const input = 'hello world  \nanother sample   \n test'; 
 
const output = input 
 
    // Remove all whitespace before and after a linebreak 
 
    .replace(/\s*\n\s*/g, '<br>'); 
 
console.log(output);

+0

完璧、ありがとう: – Tom

+0

@Tom Glad私は助けることができました! –