如何在jQuery中用空格或单引号替换双引号?

时间:2014-01-18 11:52:26

标签: jquery string parsing replace

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-type" content="text/json;charset=UTF-8">
<title>Test</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>

<script type="text/javascript">
jQuery(document).ready(function(jQuery){
    jQuery('input[name="add_custom_search"]').click(function(){
        var searchname = jQuery("#spto_searchname").val();

        var obj = {};
        jQuery( ".searchdetails label").each(function(i, el) {
            var label = jQuery(el).text();
            /* remove double quotes */
            var labelrmvdq = label.replace('"','  ');

            var labvl = jQuery(el).next().val();
            /* replace double quotes with single */
            var labcl = labvl.replace('"',"'");

            obj[labelrmvdq] = labcl;
        });
        console.log(obj);
        var objstr = JSON.stringify(obj);
        var objleftbraces = objstr.replace("{","  ");
        var objrightbraces = objleftbraces.replace("}","  ");
        var objcomma = objrightbraces.replace(",","  ");

        alert(objcomma);

});
</script>

</head>
<body>
    <form action="" method="POST">
        <div class="searchdetails">
            <label for="Postal_Code">Postal Code</label>
            <input type="text" name="Postal_Code" value=""/>

            <label for="City">City</label>
            <input type="text" id="spto_searchname" name="City" value=""/>      

            <input type="submit" name="add_custom_search">
        </div>
    </form>
</body>
</html>

当前输出:

  "Postal Code":"654132"  "City":"Portsmouth"  

预期输出:

  Postal Code: '654132' City:'Portsmouth'

1 个答案:

答案 0 :(得分:3)

为什么要使用var objstr = JSON.stringify(obj);然后从字符串中获取结果?

直接从对象构建结果。

示例:

var result = $.map({"Postal Code":"654132", "City":"Portsmouth"}, function(value, key) { 
   return key+": '"+value+"'";
}).join(' ');