簡體   English   中英

如何在開始和結尾處修剪空格和換行,並用js中的單個替換多個換行和寬行

[英]How to trim spaces and new lines from start and end and replace multiple new lines and wide spaces with single in js

樣本注釋

您好伴侶...我遇到的一個問題可能對您來說很簡單,但對我來說卻是一團糟...可能看起來像是一個常見問題,但我還沒有發現任何與我類似的情況。我有一個站點,用戶可以在該站點上添加評論...現在我想要的是,當用戶放置多個空格時,應該將其轉換為單個空格,並且應該使用多行新行來完成...除此之外,我還想在字符串的開頭和結尾處修剪寬闊的空間和新行...檢查示例輸入的屏幕截圖的鏈接(圖像)

這是我的代碼:

 $(document).on('keydown','.addComment',function(e){
    var id = $(this).attr('id').match(/\d+/);
    var p_id = Number(id);
    var comment_box = '#comment_box_'+id;
    var content = $(comment_box).html();
    content = content.replace(/\n/g, '<br>'); //replacing new line with <br>
    if (e.which === 13 && e.shiftKey !== true) {

        if (content.length > 0  ) {

            $.ajax({

                type : 'POST',
                url  : 'update.php',
                data: ({
                    content: content,
                    id: p_id,
                    act: "add_cmnt"
                }),
                success : function()
                {
                    update_ca("comment_area_"+id, true);
                }
            }); //End of Ajax
        }
        return false;
        }
        });

這是html輸入的代碼:

<p contenteditable="true" class=" addComment" id="comment_box_***"></p>

您可以嘗試以下代碼:

content = content.replace(/\n+/gm, '\n').replace(/\u0020+/gm, ' ').replace(/\n/g, '<br>');

最好的祝福。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM