传递带空格的字符串变量

Passing string variable with spaces

本文关键字:字符串 变量 空格      更新时间:2023-09-26

在下面的代码中:

    <script type="text/javascript">
        function updateView(set) {
            $.post("<?php echo base_url("/show_cards/load_page")."/"; ?>"+set, function( data ) {
                $( "#content" ).html( data );
            });
        }
    </script>

"set"是一个字符串变量,其中可以有空格。我注意到当它有空格时它无法正常工作。我该如何解决这个问题?

编辑:为了清楚起见,我想保持空间完好无损。

注意:$.trim() 现在已弃用 .trim()

使用 set.trim() 删除前导空格或尾随空格,以及

set.replace(/ /g,"+")  

encodeURI(set)

保留字符串内的空格
(参考什么时候应该使用转义而不是编码URI/encodeURIComponent?)

要一次性完成这两项操作,只需将它们链接起来即可

set.trim().replace(/ /g,"+")

请注意,如果您愿意,可以使用 %20 而不是加号。

但它不是一个参数吗?如果是这样,也许您想将其传递为

$.post("<?php echo base_url("/show_cards/load_page")."/"; ?>",
  {"set":set.trim().replace(/ /g,"+")},

你必须用replace() '%20'替换中间空间(' '),并使用trim()消除边界空间(' '):

<script type="text/javascript">
    function updateView(set) {
    set=set.trim().replace(/ /g, '%20');
        $.post("<?php echo base_url("/show_cards/load_page")."/"; ?>"+set, function( data ) {
            $( "#content" ).html( data );
        });
    }
</script>

使用 Trim

<script type="text/javascript">
        function updateView(set) {
          var set=$.trim(set);// by this  leading or trailing spaces removes  
            $.post("<?php echo base_url("/show_cards/load_page")."/"; ?>"+set, function( data ) {
                $( "#content" ).html( data );
            });
        }
    </script>

您也可以使用 string.replace

  var set=  set.replace(/ /g,"+") ;// like that way in this all the spaces removes