开发者

Javascript Jquery: extract string from value and compose URL with this string

I am using an autocomplete Javascript function, and I need to extract the last 5 characters from 'value' and then compose URL for onSelect.

The function I am using is:

<script type="text/javas开发者_Go百科cript">
    var options, a;
    jQuery(function(){
      var onAutocompleteSelect = function(value, data) {
          window.open('ITEM.PRO?id='+ value);
        }

      options = { 
      serviceUrl:'JQUERY-SEARCH.pro',
      onSelect: onAutocompleteSelect,
       };
      a = $('#query').autocomplete(options);

    });
    </script>

When I click on search result it loads "ITEM.PRO?id=Article Brand Model Year Description 35612", but I need load "ITEM.PRO?id=35612"

Please could you help me? I am a totally newbie with JS. Thank you all in advance!


Instead of window.open('ITEM.PRO?id='+ value); could you do this?

window.open('ITEM.PRO?id='+ value.split(' ').pop());


There are a few different ways to acheive this.

This simplest is to add

value = value.slice(-5);

right before

window.open('ITEM.PRO?id='+ value);

This sets value to its last 5 characters. Read here about the String.slice function.

If you want set the value to the last 'word', so to speak, delimited by spaces, you could do this instead:

value = value.split(" ").pop();

Another method would be to take the last continuous string of digits in the value. For that, you could use this:

value = value.match(/\d+/).pop();

Which method you use, of course, depends on what would work most reliably with the input you have.


Try this

var onAutocompleteSelect = function(value, data) {
          window.open('ITEM.PRO?id='+ value.substring(value.length-5));
        }


This is a terrible solution, but will work in the case you listed. I will edit if you post more details:

<script type="text/javascript">
    var options, a;
    jQuery(function(){
      var onAutocompleteSelect = function(value, data) {
          window.open('ITEM.PRO?id='+ value.match(/\d+/)[0]);
        }

      options = { 
      serviceUrl:'JQUERY-SEARCH.pro',
      onSelect: onAutocompleteSelect,
       };
      a = $('#query').autocomplete(options);

    });
</script>

value.match(/\d+/)[0] will match any digits in your string as any array, so we take the first item in that array.


When your IDs exceed 5 digits, your code will break (as has been stated in comments). You can also use the .split approach mentioned by @bordoz, the disadvantage being that spaces in any of the other words would break this solution. Or you could use:

var url = 'ITEM.PRO?id='+ value.replace(/[^\d\.]/g,'');

Which would fail only if any of the other word contain numbers. Which one best fits your situation?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜