简体   繁体   English

如何在自动完成中用空格替换下划线?

[英]How do I replace underscores with spaces in autocomplete?

I'm using jquery-ui to create a search dropdown, but I'd like to replace underscores with spaces in the dropdown results.我正在使用 jquery-ui 创建搜索下拉列表,但我想在下拉结果中用空格替换下划线。 I've tried.replace on the source but it doesn't seem to work.我已经在源代码上尝试过替换,但它似乎不起作用。

Below is my autocomplete code.下面是我的自动完成代码。 How do I use .replace(/_/g, " ") on it?我该如何使用.replace(/_/g, " ")呢?

Thank you.谢谢你。

$(document).ready(function(){
    
    var alls = $.each([
    
    'Dr._Peppins',
    'Spain',
    'index',
    
    ],
    
    $( "#userInput" ).autocomplete({
    
    source: alls
    
    });
    
});

Try this:尝试这个:

 source: alls.replace("_", " ");

Consider the following.考虑以下。

 $(function() { var alls = [ 'Dr._Peppins', 'Spain', 'index', ]; function undScore2Space(word) { return word.replace("_", " "); } function filterArray(arr) { $.each(arr, function(i, e) { arr[i] = undScore2Space(e); }); return arr; } $("#userInput").autocomplete({ source: function(req, resp) { var results = $.ui.autocomplete.filter(alls, req.term); resp(filterArray(results)); } }); });
 <link rel="stylesheet" href="//code.jquery.com/ui/1.13.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-3.6.0.js"></script> <script src="https://code.jquery.com/ui/1.13.1/jquery-ui.js"></script> <div class="ui-widget"> <label for="userInput">Input: </label> <input id="userInput"> </div>

In your example, you perform an Each.在您的示例中,您执行每个。 This is not properly formed and should generate an error.这不是正确的格式,应该会产生错误。

In the case of an array, the callback is passed an array index and a corresponding array value each time.在数组的情况下,回调每次都会传递一个数组index和一个对应的数组value (The value can also be accessed through the this keyword, but Javascript will always wrap the this value as an Object even if it is a simple string or number value.) The method returns its first argument, the object that was iterated. (该值也可以通过this关键字访问,但 Javascript 始终将this值包装为 Object,即使它是一个简单的字符串或数字值。)该方法返回其第一个参数,即迭代的 object。

So you do not want to initialize Autocomplete on each item in the array.所以你不想在数组中的每个项目上初始化自动完成。 You can modify each part if you choose, yet if you expect the source to contain these characters, it would be best to filter them out after the lookup.如果您愿意,您可以修改每个部分,但如果您希望源包含这些字符,最好在查找后将它们过滤掉。

You can make use of a function for source and perform events this way.您可以使用 function 作为source并以这种方式执行事件。

You can also do the following:您还可以执行以下操作:

$(document).ready(function(){
    var alls = [];
    $.each([
      'Dr._Peppins',
      'Spain',
      'index'
    ], function(index, elem){
      alls.push(elem.replace("_", " "));
    });
    $("#userInput").autocomplete({
      source: alls
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM