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

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/javascript">
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?

Related

remove all Decimals and single numbers from array / string

so my script generates a big blob of "Piano Notes" which are similar to...
var songNotes = "...";
the large Piano notes content
and my problem is between the piano notes which i need [also in the fiddle] there are empty ",," and decimal numbers.. so i cant figure out how to remove the empty
,, and decimals as big as
"1.0416666666642413,0.625,0,g3,1498.9583333333358,,0,c3,1.0416666666642413,0.625,0,c3"
and i want them removed except the the needed words which are
var theRightOnes = "s2,as2,cs3,ds3,fs3,gs3,as3,gs3,cs4,ds4,fs4,cs3,as4,gs4,ds5,a2,cs4,b2,c3,a3,ds4,b3,c4,as3,gs2,e3,c3,c4,cs3,ds3,a4,fs3,gs3,as3,g3,f3,b4,c5,a3,d4,as2,e4,g4,d3,b3,b2,f4,a2,d4,e4,cs5,gs1,e2,c2,c3,cs2,ds2,a3,fs2,gs2,as2,g2,f2,b3,c4,a2,d3,as1,e3,g3,d2,b2,b1,f3,a1,d5,e5";
so can anyone give me a clue on how this can be accomplished?
if anyone needs more info then i am ready oblige to do so..
Regards - Adarsh Hegde
var notesArr = songNotes.split(",");
var len = notesArr.length;
while(len--) {
if(!notesArr[len] || !isNaN(parseInt(notesArr[len], 10))) {
notesArr.splice(len, 1);
}
}
songNotes = notesArr.join(",");
I think you want to remove all the numbers from notes.
You can say like bellow
var notes = songNotes.split(",").filter(function(note){
return isNaN(note);
});
console.log(notes);
You can use Array.filter (see MDN) to weed out unwanted values:
var wantedNotes = songNotes.split(',')
.filter(function (v) {
return isNaN(+v) && v.trim().length
});
jsFiddle
just use regular expression,like this:
var a = "1.0416666666642413,0.625,0,g3,1498.9583333333358,,0,c3,1.0416666666642413,0.625,0,c3";
console.log(a.replace(/\b(\d+(\.\d+)?),+/g,""));

is it possible to check the XMLHttpRequestObject.responseText value using if condition

Is it possible to check the XMLHttpRequestObject.responseText value using if condition instead of just displaying it?
I have tried like this.
var a=XMLHttpRequestObject.responseText;
if(a=="false")
{
document.getElementById("show_mark").innerHTML =a;
}
I know its wrong,but i need to do like this.Is there any other alternative way for doing this?Help me i am completely a newbie to AJAX.
It is possible that the response text has added white spaces. To remove white spaces at the start and end of a string use string.trim().
In your case a=a.trim()
If trim is not available in your browser's JavaScript interpreter add in
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g, '');
};
}
Source
Finally i found the mistake.Its not the white spaces around the value.Actually its all the html tags like <html><body>false</body> etc., I removed these characters with the help of this code. I got the answer.
var a=XMLHttpRequestObject.responseText;
a = a.replace(/&(lt|gt);/g, function (strMatch, p1){
return (p1 == "lt")? "<" : ">";
});
var b = (a.replace(/<\/?[^>]+(>|$)/g, "")).trim();
if(b=="false")
{
document.getElementById("show_mark").innerHTML =b;
}
Thanks for the support.

Find and remove text from input value string

Our form has a hidden input that contains all the required values we send to the server for server-side validation. This is formed of a comma-separated string:
i.e. <input type="hidden" value="name,address,telephone,email">
We now have new inputs (i.e. website) that appear on a radio button check and I can successfully add these to the value="" string:
var nowReq = $('input[name="required"]').val();
if ($('#website').is(':checked')) {
$('input[name="required"]').val(nowReq + ',website');
}
But when a different radio is checked, I can't get it to remove ,website from the string.
I believe I need to grab the string, split it by comma, find and remove website and then re-join the string, but I'm not sure how to implement this (or if this is even the best way):
if ($('#fax').is(':checked')) {
var splitReq = nowReq.split(',');
// Something goes here?
$('input[name="required"]').val(nowReq2);
}
You can use string.indexOf(searchValue); and string.replace(oldValue, newValue); to search and remove non-selected elements or better pass Regular expression in the first parameter of string.replace(regex, newValue):
Non-regex Example:
var nowReq = $('input[name="required"]').val();
if ($('#website').is(':checked')) {
nowReq = nowReq + ',website';
}
else {
if(string.indexOf(',website') > -1) // If website is the last element
nowReq = nowReq.replace(',website', '');
else if(string.indexOf('website,') > -1) // If website is not the last element
nowReq = nowReq.replace('website,', '');
}
$('input[name="required"]').val(nowReq);
You simply need to remove the last element in your array and join it with the ',' character :
splitReq.pop();
$('input[name="required"]').val(splitReq.join(','));
Try:
var splitReq = nowReq.split(',website').join("");
the following would work in most cases:
var s = "name,address,telephone,email";
s = s.replace(",address", "").replace("address,", "").replace("address", "");
I'd suggest that you avoid parsing the value string, and simply recalculate the value on the change of the relevant input elements; the following is a demonstrative example because of the lack of information presented in the question (a more specific example could be provided if we can see your HTML, and current jQuery, rather than a description of it):
$('input[type="checkbox"]').on('change', function(){
var requiredString = $('input[type="checkbox"]').map(function(){
if (this.checked) {
return this.value;
}
}).get().join(',');
$('input[name="required"]').val(requiredString);
}).change();
JS Fiddle demo.
References:
change()
filter()
get()
map()
on()

Numeric field just accept number and `,`

How can change this numeric(normal number formatting) js code as that just accept number and ,, mean don't accept word or character(like: -, =, +,!, and ...) just accept number and ,. How is it?
Example: http://jsfiddle.net/fQb9X/
$(document).delegate('input.numeric:text', 'keyup', function () {
$val = $(this).val().match(/[0-9]/g).reverse().join("").match(/[0-9]{1,3}/g).join(",").match(/./g).reverse().join("");
$(this).val($val)
});
I actually wrote something just like this recently:
var oldnumber='';
var $ctrl=$('input[name=passport_number]');
$ctrl.focusout(function () {
if (isFinite($ctrl.val()) || $ctrl.val()==',') {
oldnumber=$ctrl.val();
} else {
$ctrl.attr('value',oldnumber);
}
});
Basically, if you type in a valid answer, it remembers that value. If you write anything but a number or a ',', the field is set back to its previous valid value.
My solution is decently short and pretty darn clean if you ask me. It checks if it is a number, if not, it denies your entry.
EDIT
If you want it to happen while you type, try this:
$('input').bind('keyup change',function(){
var v = parseInt($(this).val());
$(this).val((isNaN(v) && v!=',')?'':v);
});
Hope that helps :)

JavaScript Replace all odd behavior

I want this code:
function renderTemplate(temp,content){
for (var i in temp){
replace = new RegExp("["+i+"]",'g');
content = content.replace(i,temp[i]);
}
return content;
}
var temp = {'status':'ok','id':150};
var content = "your status is [status], again! your status is [status], and your id is [id], yes[id]";
alert(renderTemplate(temp,content));
To genrate me this string:
your status is ok, again! your status is ok, and your id is 150, yes 150
Instead, I get:
your ok is [status], again! your status is [status], and your 150 is [id], yes[id]
Look where the ok was placed....
you can run it here: http://jsfiddle.net/v9vzd/
Thanks
Although Adrian Lang's fine answer should get you going, I would argue that you're not taking the best approach. Compiling regexes from a variable can be awkward when it comes to escaping, and it's generally slower performance-wise.
If it were me, I would take advantage of passing a function to replace():
function renderTemplate(temp, content) {
return content.replace(/\[([^[\]+)\]/g, function ($0, key) {
return temp[key];
});
}
Working demo: http://jsfiddle.net/AKsHb/
This works because the sub-expression capture, ([^\]]+) is passed to the replacing function as the second argument — labelled key in our function above — and this matches anything between a literal [ and ].
Try the following code:
function renderTemplate(temp,content){
for (var i in temp){
replace = new RegExp("\\["+i+"\\]",'g');
content = content.replace(replace,temp[i]);
}
return content;
}
var temp = {'status':'ok','id':150};
var content = "your status is [status], again! your status is [status], and your id is [id], yes[id]";
alert(renderTemplate(temp,content));
You didn’t use the RegExp object you created. Furthermore, square brackets create a character class, so oyu have to escape the square bracket (and in the RegExp constructor call, you have to escape the escaping backslash, so it is two backslashes).

Categories

Resources