I have a string which is a car number plate. But for display purposes I what to add a space after the fourth char in this string. The data comes from a data service so I have to do this on the front-end
eg. AF13BXP to this AF13 BXP
The code below doesn't seem to work:
var $regtext = $('#regNumber');
if ($regtext.length > 0)
{
var regtext = $regtext.text(),
newRegtext = regtext.replace(/[\n\s]/g, '');
console.log(newRegtext);
}
Simple and clear way to do this, without regex:
var $regtext = $('#regNumber');
if ($regtext.length > 0)
{
var regtext = $regtext.text(),
newRegtext = regtext.substr(0, 4) + " " + regtext.substr(4);
console.log(newRegtext);
}
It's also pretty fast too: runs 10,000 times in 351ms, faster than splitting and joining etc. Good if you'll be processing loads of data from the webservice.
You can use following jquery : Demo
$('.test').keyup(function() {
var foo = $(this).val().split(" ").join("");
if (foo.length > 0) {
foo = foo.match(new RegExp('.{1,4}', 'g')).join(" ");
}
$(this).val(foo);
});
If you want to use regex the following should do it.
newRegtext = regtext.replace(/^(.{4})/,'$1 ')
Try this code
$(document).ready(function(e) {
var $regtext = $('#regNumber');
var $regtext = $regtext.text();
if ($regtext.length > 0)
{
regCheck = /^([A-Z1-9a-z]{1,4})([A-Z1-9a-z]*)$/;
regtext = regCheck.test($regtext);
newRegtext = $regtext.replace(regCheck,"$1 $2");
alert(newRegtext);
}
});
Related
I'm no professional and after research, I wasn't able to find a solution.
I have a JavaScript source code for a SharePoint list to implement the InstantListFilter (https://archive.codeplex.com/?p=instantlistfilter) which works!
But I would like to update the source code so that the filter is NOT case sensitive. I was able to replace the the filter word (val) to uppercase (val = val.toUpperCase()). But I have no idea how to get the list-text to uppercase.
$("table.ms-listviewtable").children("tbody").each(function() {
$(this).children("tr").each(function() {
var mismatch = false;
$(this).children("td").each(function(colIndex) {
if (mismatch) return;
if (filterValues[colIndex]) {
var val = filterValues[colIndex];
// replace double quote character with 2 instances of itself
val = val.replace(/"/g, String.fromCharCode(34) + String.fromCharCode(34));
val = val.toUpperCase(); //my adaption, working for the filter word
$(this).val = $(this).val().toUpperCase(); //not working for the list-text
// verifies the filter word.
if ($(this).is(":not(:contains('" + val + "'))")) {
mismatch = true;
}
}
});
if (mismatch) {
$(this).hide();
} else {
$(this).show();
}
});
});
Does anybody have a solution?
Would be happy with a short reply!
The solution you are trying will also modify the input value to upper case, i'm not sure you want that? Maybe you could assign the input value to a var and see if it contains the text with String.indexOf()
...
val = val.toUpperCase(); //my adaption, working for the filter word
var inputVal = $(this).val().toUpperCase();
// indexOf = -1 means that inputVal does not contain val
if (inputVal.indexOf(val) === -1) {
mismatch = true;
}
...
thanks for reply!!!
I got it:
var inputVal = $(this).text().toUpperCase();
//alert(inputVal);
// verifies the filter word.
// indexOf = -1 means that inputVal does not contain val
if (inputVal.indexOf(val.toUpperCase()) === -1) {
mismatch = true;
}
I'm running the following code to set a limit on characters in a textarea:
(function($){
$.fn.extend({
limit: function(limit,element) {
var interval, f;
var self = $(this);
$(this).focus(function(){
interval = window.setInterval(substring,100);
});
$(this).blur(function(){
clearInterval(interval);
substring();
});
substringFunction = "function substring(){ var val = $(self).val();var length = val.length + carriages;if(length > limit){$(self).val($(self).val().substring(0,limit));}";
if(typeof element != 'undefined')
substringFunction += "if($(element).html() != limit-length){$(element).html((limit-length<=0)?'0':limit-length);}"
substringFunction += "}";
eval(substringFunction);
substring();
}
});
})(jQuery);
The area my users are entering text into can fit a maximum of 1500 characters. The problem is that it can only fit a maximum of 10 lines. If they enter 25 characters on one line before entering a carriage return, the characters total needs to be at 150, not 26.
How can I accomplish this?
var string = "foo\nbar\nbaz";
console.log(string);
// foo
// bar
// baz
var lines = string.split(/\n/).length;
Simply split the string by every new lines, and then see how many lines you have.
Another solution using regex that is always very efficient. Note that this solution counts retuen carriages, NOT lines
const string = "foo\nbar\nbaz";
const lines = (string.match(/\n/g) || []).length;
console.log(lines);
I don't get it.
I can't increment the Tweet-ID ...
Here is a demo: http://jsbin.com/idupoq/1/edit
glb = {};
glb.lastTweetId = 0;
getTweets();
function getTweets()
{
console.info('# LAST ID');
console.log(glb.lastTweetId);
console.info('# TEST 1');
glb.lastTweetId++;
console.log(glb.lastTweetId);
console.info('# TEST 2');
glb.lastTweetId = glb.lastTweetId+1;
console.log(glb.lastTweetId);
console.info('# TEST 3, OK IS INT BUT PARSE AGAIN ');
glb.lastTweetId = parseInt(glb.lastTweetId);
glb.lastTweetId++;
console.log(glb.lastTweetId);
$.getJSON('http://search.twitter.com/search.json?q=%23wwm&since_id='+glb.lastTweetId+'&include_entities=true&result_type=mixed&lang=de&callback=?', function(data, textStatus)
{
if(data.results.length > 0)
{
glb.lastTweetId = data.results[0]['id'];
}
glb.tm= setTimeout('getTweets();',5000);
});
}
Thanks in advance!
This happens because the received ID is out of range of Number format, e.g.
271567725082578940 + 1 = 271567725082578940
You should use special libraries to work with large numbers. Some examples:
https://github.com/jtobey/javascript-bignum
http://jsfromhell.com/classes/bignumber
As others have said already, it is because of Number cannot express 271567725082578941. If all you ever want to do to this number is to increase it by one, then the following function should be all you need:
function stringInc(v){
var digits = v.toString().split('');
var i = digits.length-1;
while (digits[i]==9 && i>0){
digits[i] = 0;
i--;
}
digits[i] = 1+parseInt(digits[i]);
return digits.join('');
}
If you expect to want to do something more with the number, then you might be better off using a BigNumber library as suggested by VisioN.
Either way, you should note that you cannot read the tweet id from data.results[0]['id'], because that is interpreted as a Number and rounded to 271567725082578940. You need to use data.results[0]['id_str'].
See updated jsbin here: http://jsbin.com/idupoq/19/. Notice the console is logging the result from the server:
...
"geo":null,
"id": 271580395022217200,
"id_str":"271580395022217216",
"iso_language_code":"de"
...
So the value 271567725082578940 that you have been observing is incorrect as well.
Dirty but short
http://jsbin.com/idupoq/18/edit
glb.lastTweetId = ''+data.results[0]['id']+'';
var lastTwoDig = parseInt(glb.lastTweetId.substr(glb.lastTweetId.length-2));
var startDigit = glb.lastTweetId.substring(0, glb.lastTweetId.length-2);
lastTwoDig++;
if(lastTwoDig==01){ lastTwoDig = '01'; }
console.log(glb.lastTweetId);
console.log(' '+startDigit+''+lastTwoDig+' ');
I am copying a function that will take a youtube/vimeo url and return what site the video came from (vimeo/yt) as well as the video id.
Here's what I have so far: http://jsfiddle.net/csjwf/181/
<strong>Result:</strong>
<div id="result"></div>
function parseVideoURL(url) {
url.match(/^http:\/\/(?:.*?)\.?(youtube|vimeo)\.com\/(watch\?[^#]*v=(\w+)|(\d+)).+$/);
return {
provider : RegExp.$1,
id : RegExp.$1 == 'vimeo' ? RegExp.$2 : RegExp.$3
}
}
var result = document.getElementById("result");
var video = parseVideoURL("http://www.youtube.com/watch?v=PQLnmdOthmA&feature=feedrec_grec_index");
result.innerHTML = "Provider: " + video.provider + "<br>ID: " + video.id;
var video = parseVideoURL("http://vimeo.com/22080133");
result.innerHTML += "<br>--<br>Provider: " + video.provider + "<br>ID: " + video.id;
Output:
Result:
Provider: youtube
ID: PQLnmdOthmA
--
Provider: vimeo
ID: 2208013
However, notice how for vimeo vids, if the url ends in the ID, the last number is always cut off. If you add a slash to the end of the vimeo url the id is pulled fully.
The .+$ at the end is requiring at least one character after the last digit that is captured as a string of digits. That will chop one digit off what is captured. Is there a reason you have that there?
You can change the last + to a * like this:
/^http:\/\/(?:.*?)\.?(youtube|vimeo)\.com\/(watch\?[^#]*v=(\w+)|(\d+)).*$/
or even better, get rid of the end part entirely since it doesn't look like it's needed:
/^http:\/\/(?:.*?)\.?(youtube|vimeo)\.com\/(watch\?[^#]*v=(\w+)|(\d+))/
Here's a bit safer way to write your function that allows for any order of the query parameters in the youtube URL and doesn't put stuff into the regex that doesn't need to be there. The code is longer, but it's much more robust and would be much easier to add more providers:
function parseVideoURL(url) {
function getParm(url, base) {
var re = new RegExp("(\\?|&)" + base + "\\=([^&]*)(&|$)");
var matches = url.match(re);
if (matches) {
return(matches[2]);
} else {
return("");
}
}
var retVal = {};
var matches;
if (url.indexOf("youtube.com/watch") != -1) {
retVal.provider = "youtube";
retVal.id = getParm(url, "v");
} else if (matches = url.match(/vimeo.com\/(\d+)/)) {
retVal.provider = "vimeo";
retVal.id = matches[1];
}
return(retVal);
}
Working version here: http://jsfiddle.net/jfriend00/N2hPj/
Here is an updated version that also works with youtu.be and youtube.com/embed urls using #jfriend00's code and some code found here: JavaScript REGEX: How do I get the YouTube video id from a URL?.
EDIT: Updated my answer (and the fiddle) with a function that actually works. :-)
function parseVideoURL(url) {
function getParm(url, base) {
var re = new RegExp("(\\?|&)" + base + "\\=([^&]*)(&|$)");
var matches = url.match(re);
if (matches) {
return(matches[2]);
} else {
return("");
}
}
var retVal = {};
var matches;
var success = false;
if ( url.match('http(s)?://(www.)?youtube|youtu\.be') ) {
if (url.match('embed')) { retVal.id = url.split(/embed\//)[1].split('"')[0]; }
else { retVal.id = url.split(/v\/|v=|youtu\.be\//)[1].split(/[?&]/)[0]; }
retVal.provider = "youtube";
var videoUrl = 'https://www.youtube.com/embed/' + retVal.id + '?rel=0';
success = true;
} else if (matches = url.match(/vimeo.com\/(\d+)/)) {
retVal.provider = "vimeo";
retVal.id = matches[1];
var videoUrl = 'http://player.vimeo.com/video/' + retVal.id;
success = true;
}
if (success) {
return retVal;
}
else { alert("No valid media id detected"); }
}
And a working jsfiddle: http://jsfiddle.net/9n8Nn/3/
Out of the two stackexchange answers, this is the code that worked best for me in the end.
To simplify your regex I would use haystack.indexOf(needle) to determine if the url is vimeo or youtube and then apply site specific regex. Much easier, and later you can add video sites without overly complicating the regex.
Last number gets cut off because you're using ".+" at the end, which means "one or more of any character". Replace the + with a *, meaning "zero or more".
url.match(/^http:\/\/(?:.*?)\.?(youtube|vimeo)\.com\/(watch\?[^#]*v=(\w+).+|(\d+))$/);
Remove the last . and the end matching
url.match(/^http:\/\/(?:.*?)\.?(youtube|vimeo)\.com\/(watch\?[^#]*v=(\w+)|(\d+))/);
I'm working on a form and I'd like to mask the input of the phone numbers. The plugins what I found aren't okay for me since the area code could be 1 or 2 character long.
What I'd like to do is the following:
when the user types his number after the first two character the script inserts a space on keyup, then after the next three and later after every fourth character.
So when someone types 44444444444 then in the textbox appears 44 44 444 4444.
I must check the second group as well, and when someone types there for example 1, the the number must look like: 44 1 444 4444
Is any solution to do that?
You could do something like this:
http://jsfiddle.net/ffwAA/4/
Which applies this function to the string to get the desired formatting:
function formatCode(str){
var result = str;
str = str.replace(/\D+/g, "");
var m = str.match(/^(\d\d)(?:([2-90]\d|1)(?:(\d\d\d)(\d+)?)?)?$/);
if(m){
result = m[1] + " ";
if(m[2]) result += m[2] + " ";
if(m[3]) result += m[3] + " ";
if(m[4]){
result += m[4].split(/(\d{4})/).join(" ");
result = result.replace(/\s+/g, " ");
}
}
return result;
}
And using this jQuery to set it up:
function update(obj){
var val = obj.value;
var got = formatCode(val);
if(got != val)
obj.value = got;
}
var timer;
var prev_val = "";
$('#code').keyup(function(){
clearTimeout(timer);
// when adding numbers at the end of input, update at once
// don't want to update when editing in the middle of the string or removing parts of it
// because it would move the carret location to the end of input, and make it unusable
if(this.value.indexOf(prev_val) == 0){
update(this);
prev_val = this.value;
return;
}
prev_val = this.value;
// in other cases update 1 second after the changes are done
timer = setTimeout(update, 1000, this);
});
Have you tried the maskedInput plugin?
http://digitalbush.com/projects/masked-input-plugin/
I think it can solve your problem.
Hope this helps. Cheers