Loại bỏ khoảng trắng dư thừa trong văn bản bằng JavaScript | How to replace multiple spaces in a string to single space with JavaScript?


Một function(hàm) JavaScript hỗ trợ xử lý dữ liệu để loại bỏ khoảng trắng dư ở đầu, cuối, và các khoảng trắng dư thừa trong một đoạn văn bảng.

Hàm - Function:

function trimSpace(str) {
    return str.replace(/^\s*/, "").replace(/\s*$/, "");
}


Ví dụ - Example:

http://jsfiddle.net/j53zf2tv/1/

<!DOCTYPE html>
<html>
<body>

<p>VNLIVES.NET - Demo remove top, end, and multiple spaces in text.</p>

<button onclick="myFunction()">Run Demo</button>

<script>
function myFunction() {
    var text = "   VNLIVES.NET   Welcome    you visting   website .";
    text = trimSpace(text);
    alert(text);
}


function trimSpace(str)
{
    return str.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,"").replace(/\s+/g," ");
}

</script>

</body>
</html>


Kết quả - Result:





Write: +Bui Ngoc Son





No comments:

Post a Comment