Random serial generating regex separator - javascript

The output of this code separates each 4 digits by a hyphen(-) with the regex \w, but it doesn't work if I replace \w to other regular expressions. Why is that?
This one works perfectly.
function gen(length, separator) {
var license = new Array(length + 1).join((Math.random().toString(36) + '00000000000000000').slice(2, 18)).slice(0, length);
return license.toUpperCase().replace(/(\w{4})/g, '$1' + separator).substr(0, length + Math.round(length/4)-1);
}
document.write(gen(16, '-'));
This one does not separates by a hyphen each 4 digits.
function gen(length, separator) {
var license = new Array(length + 1).join((Math.random().toString(36) + '00000000000000000').slice(2, 18)).slice(0, length);
return license.toUpperCase().replace(/([A-Z]{4})/g, '$1' + separator).substr(0, length + Math.round(length/4)-1);
}
document.write(gen(16, '-'));

I think you need something like this:
function gen(length, separator) {
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var text = '';
for( var i=0; i < length; i++ ) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
if(i%4 == 3 && i<length-1) text += separator;
}
return text;
}
document.write(gen(16, '-'));

Related

Truncated a string with a number of characters without truncating words

I want to truncate a string with a limit of characters and a condition for the last character that should be a space (this way I have no truncated words)
Example :
var sentence = "The string that I want to truncate!";
sentence.methodToTruncate(14); // 14 is the limit of max characters
console.log("Truncated result : " + sentence); // Truncated result : The string
You can use truncate one-liner below:
const sentence = "The string that I want to truncate!";
const truncate = (str, len) => str.substring(0, (str + ' ').lastIndexOf(' ', len));
console.log(truncate(sentence, 14));
Here's how you can truncate by words and given limit -
String.prototype.methodToTruncate = function(n) {
var parts = this.split(" ");
var result = "";
var i = 0;
while(result.length >= n || i < parts.length) {
if (result.length + parts[i].length > n) {
break;
}
result += " " + parts[i];
i++;
}
return result;
}
var sentence = "The string that I want to truncate!";
console.log("Truncated result : " + sentence.methodToTruncate(14)); // Truncated result : The string
First you can have a max substring of your string, and then recursively remove the letters until you find spaces.
Note that this response is made without doing monkey patching and so, not extending String.prototype :
var sentence = "Hello a";
var a = methodToTruncate(sentence, 5); // 14 is the limit of max characters
console.log("Truncated result : " + a); // Truncated result : The string
function methodToTruncate(str, num) {
if(num>= str.length){ return str;}
var res = str.substring(0, num);
while (str[res.length] != " " && res.length != 0) {
console.log(res.length)
res = res.substring(0, res.length-1);
}
return res;
}

Convert string of time to cleaner format

There's usually some magical way to do something in javascript.
Take for example the string
10h49m02s
and wanting to convert it to
10 hours, 49 minutes, 2 seconds
while avoid empty hours/minutes/seconds
eg2
00h10m20s
This is what I'm doing which is probably hilarious
var arr = time.split('');
var hourMaj = arr[0];
var hourMin = arr[1];
var minMaj = arr[3];
var minMin = arr[4];
var secMaj = arr[6];
var secMin = arr[7];
var str = "";
if(hourMaj !== '0'){
str += hourMaj;
str += hourMin;
}else if (hourMin !== '0'){
str += hourMin;
}
if(hourMaj !== '0' || hourMin !== '0')
str += "hours, ";
... and on
You can actually use a regex to match your values and replace h, m and s with expanded words only if the captured texts are not zeros, like this:
var re = /\b0*(\d{1,2})h0*(\d{1,2})m0*(\d{1,2})s\b/g;
var str = '10h49m02s';
var str2 = '00h10m20s';
function func(match, h, m, s) {
var p = '';
if (h !== '0') {
p += h + " hours"
}
if (m !== '0') {
p += (p.length > 0 ? ", " : "") + m + " minutes"
}
if (s !== '0') {
p += (p.length > 0 ? ", " : "") + s + " seconds"
}
return p;
}
var res = str.replace(re, func);
document.write(res + "<br/>");
res = str2.replace(re, func);
document.write(res);
The regex - \b0*(\d{1,2})h0*(\d{1,2})m0*(\d{1,2})s\b - matches:
\b - word boundary
0* - 0 or more leading zeros
(\d{1,2}) - hours, 1 or 2 digits
h0* - h literally and 0 or more zeros
(\d{1,2}) - minutes, 1 or 2 digits
m0* - m literally and 0 or more zeros
(\d{1,2}) - seconds, 1 or 2 digits
s\b - s at the end of the "word".
Similar to stribizhev's answer, but with a much simpler regular expression. I've used reduce but a for loop is no more code and would probably be faster:
function parseTime(s) {
// Match sequences of numbers or letters
var b = s.match(/\d+|[a-z]+/gi);
var words = {h:'hour', m:'minute', s:'second'};
var result;
// If some matches found
if (b) {
// Do replacement
result = b.reduce(function(acc, p, i) {
// Only include values that aren't zero
// and skip letters - +p => NaN
if (+p) {
// Change letters to words, add plural and store in array
acc.push(+p + words[b[i+1]] + (p==1? '' : 's'));
}
// Pass the accumulator array to the next iteration
return acc;
},[])
}
// Format the result
return result.join(', ');
}
document.write(parseTime('00h00m02s') + '<br>');
document.write(parseTime('10h40m02s') + '<br>');
document.write(parseTime('10h00m51s') + '<br>');
document.write(parseTime('01h32m01s'));

Regex to allow numbers, plus symbol, minus symbol and brackets

I am trying to create a regex that allows only the following 0-9, plus symbol, minus symbol and brackets (). No limitations on length of each of the mentioned. So far I have this but it does not seem to work.
/^[0-9 -+]+$/
Hyphen - has to be at the end of charlist, else it means interval.
/^[0-9 ()+-]+$/
0-9 is possible to write shortly as \d
/^[\d ()+-]+$/
This should work for you:
^[\d\(\)\-+]+$
^ -> start of string
\d -> same as [0-9]
+ -> one or more repetitions
$ -> end of string
DEMO
var re = /^[\d\(\)\-+]+$/m;
var str = ['09+()1213+-','fa(-ds'];
var m;
var result = "";
for(var i = 0; i < str.length; i++) {
if ((m = re.exec(str[i])) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}
result += "\""+str[i]+ "\"" + " is matched:" + (m != null) + "</br>";
}
document.getElementById("results").innerHTML = result
<div id="results"></div>
To match digits, +, -, (, and ) use:
[+()\d-]+
The trick is the position of the characters inside the character class.
if (/^[+()\d-]+$/.test(text)) {
} else {
}
var re = /^[\w\(\)\-\!\+\*\&\%\$#\#\[\]\{\}\<\>\s]+$/m;
var str = ['09+()1213+-[#test#gmail{}<>','fa(-ds'];
var m;
var result = "";
for(var i = 0; i < str.length; i++) {
if ((m = re.exec(str[i])) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}
result += "\""+str[i]+ "\"" + " is matched:" + (m != null) + "</br>";
}
document.getElementById("results").innerHTML = result
<div id="results"></div>
[\d\(\)\+\-\(\)]
That should do it.
EDIT: But since some agree the escaping is too much, here ya go:
[\d+()-]

Delete part of string by index position

How can I delete a part of a string by using only the index (no regex in case the character at index exists elsewhere)?
I use this, but it seems extremely convulted!!
var str = "stringIwant to delete from";
var stringCodeLastIndex = str.length - 1;
var index2delete = 1;
var stringStart, stringEnd, finalString;
if (index2delete == 0) {
stringStart = "";
} else {
stringStart = str.substr(0, index2delete);
}
if (index2delete < stringCodeLastIndex) {
stringEnd = str.substr(index2delete + 1);
} else {
stringEnd = "";
}
finalString = stringStart + stringEnd;
substring is smart enough to handle invalid indexes on its own:
str = "someXXXstring";
del = 4;
len = 3
str = str.substring(0, del) + str.substring(del + len);
document.body.innerText += str + ","
str = "somestringXXX";
del = 10;
len = 20
str = str.substring(0, del) + str.substring(del + len);
document.body.innerText += str + ","
str = "somestring";
del = 0;
len = 200
str = str.substring(0, del) + str.substring(del + len);
document.body.innerText += str + ","
In your case, it's easier to use slice():
finalString = str.slice(0,index2delete)+str.slice(index2delete+1)
If you want to remove more characters, you can have 2 indexes:
finalString = str.slice(0,start_index)+str.slice(endindex+1)
http://www.w3schools.com/jsref/jsref_slice_string.asp
To remove one specific index from your string:
str.substr(0, indexToDelete) + str.substr(indexToDelete+1, str.length);
to remove a range of indexes from your string:
str.substr(0, startIndexToDelete) + str.substr(endIndexToDelete+1, str.length);
var str = "stringIwant to delete from";
var index2delete = 1;
arStr = str.split(""); // Making a JS Array of each characters
arStr.splice(index2delete,1); // Using array method to remove one entry at specified index
var finalString = arStr.join(''); // Convert Array to String
Result :
sringIwant to delete from
fiddle
then create a substring and use replace('your substring', '') it will replace the part of your string with a empty space

Why is this regex matching on decimals?

I have a large number of text fields that need to be evaluated onkeyup to be sure nothing is entered but numbers. Decimals are ok. So is the absence of a value.
For some reason this is matching on decimals. Eg I type 4 and then . and it flags on .
How do I correct this?
var s_in = 0;
for (var i = 10; i < 19; i++) {
var fObj = document.getElementById(field+'_'+i);
var text = fObj.value;
if (text) {
var s = parseInt(text);
var pattern = /^[+-]?(\d*\.)?\d+$/;
var result;
if ((result = pattern.exec(text)) != null) {
if (s > -1) {
s_in += s;
}
} else { // not empty and not a number
alert('The entry for Hole ' + i + ' ' + ucfirst(field) + ' is "' + text + '" This is not a number. It will be erased now.');
fObj.value = '';
fObj.focus();
return false;
}
}
}
Your regex requires one or more digits after the decimal point and you have to escape the - in the first group). If you don't want to require a digit after the decimal, then you can use this (changes a + to a * and puts \ in front of the -):
/^[+\-]?(\d*\.)?\d*$/

Categories

Resources