删除文本区域开头和结尾的空白

所以我正在做一个基本上删除空行的代码,以及删除字符串开头和结尾的空格。但是trim功能似乎不起作用我该如何解决?


这是我尝试过的代码


<textarea id="a">

 a


 b

 c   

</textarea><button id="c">Remove blank lines</button><textarea id="b"></textarea>

jQuery代码是:


jQuery(function ($) {

    $("#c").on("click", function () {

        var avalue = $.trim($('#a').val());

        var newVal = avalue.replace(/^\s*[\r\n]/gm, '');

        $('#a').val(newVal);


    });

})


温温酱
浏览 143回答 2
2回答

长风秋雁

Trim() 就是为此目的而制作的,它删除了字符串开头和结尾的空格&nbsp; &nbsp; jQuery(function ($) {&nbsp; &nbsp; $("#c").on("click", function () {&nbsp; &nbsp; &nbsp; &nbsp; var avalue = $.trim($('#a').val());&nbsp; &nbsp; &nbsp; &nbsp; var newVal = avalue.trim();&nbsp; &nbsp; &nbsp; &nbsp; $('#a').val(newVal);&nbsp; &nbsp; });})

天涯尽头无女友

您可以使用修剪,它将删除周围的所有空格(左或右)。之间的空间将被保留。`<script>&nbsp; &nbsp; $(document).ready(function(){&nbsp; &nbsp; &nbsp; &nbsp; var myStr = $(".original").text();&nbsp; &nbsp; &nbsp; &nbsp; var trimStr = $.trim(myStr);&nbsp; &nbsp; &nbsp; &nbsp; $(".trimmed").html(trimStr);&nbsp; &nbsp; });</script></head><body>&nbsp; &nbsp; <h3>Original String</h3>&nbsp; &nbsp; <pre class="original">&nbsp; &nbsp; &nbsp; Paragraph of text with&nbsp; &nbsp; &nbsp; &nbsp;multiple&nbsp; &nbsp; white&nbsp; &nbsp;spaces before and after.&nbsp; &nbsp; &nbsp; &nbsp;</pre>&nbsp; &nbsp; <br>&nbsp; &nbsp; <h3>Trimmed String</h3>&nbsp; &nbsp; <pre class="trimmed"></pre></body>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript