Not replace hex code in jquery preview - javascript

i am making a basic system to replace some characters.
Example:
\t - Replace for tab-size 4
\n - Replace for
this working very good, but, when is replaced a hex code (In this case the format is: {FFFFFF}) not work if the code is on pos 1 or more. Only work if the code is in first pos of string of the textarea
code =
$(document).ready(function()
{
$('#dialog_edit_input').keyup(function()
{
var val = $(this).val();
var start = -1, end = -1;
// Backspaces (\t, \n)
val = val.replace(/\\n/g, "<br />");
val = val.replace(/\\t/g, "<p class=\"create_t\"></p>");
// Extraer colores hex PAWN
start = val.search("{");
end = val.indexOf("}", (start != -1 ? start+6 : 0));
var is_posible = ((start != -1 && end != -1) && end == start + 7);
var _color_real = is_posible ? val.substr(start, end+1) : null;
var _color = _color_real != null ? _color_real.substr(1, _color_real.length-2) : null;
if(is_posible)
val = val.replace(_color_real, "<span style=\"color: #" + _color + "\">");
console.log(end);
$('#agregar_resultado').html(val);
});
});

You can use a regular expression like you did for the other substitutions:
val = val.replace(/\{([0-9A-Fa-f]{6})\}/g, '<span style="color: #$1">');
Notes:
The parentheses in the regular expression create a group. That means the six hex digits will form the first (and only) group. Notice that the braces are not within the parentheses. They are necessary for a match to take place, but they are not part of the group.
The $1 in the substitution string will be replaced with the value of the first matched group, which in this case is the six hex digits.
jsfiddle
As for why your code is not working as written, you are looking for only one occurrence. Instead, you would need to have a loop.
var pos = 0;
while (pos < val.length) {
var start = val.indexOf('{', pos);
if ((start >= 0) && ((start + 7) < val.length)) {
if (val.charAt(start + 7) == '}') {
var color = val.slice(start + 1, start + 7);
var replacement = '<span style="color: #' + color + '">';
val = val.slice(0, start) + replacement + val.slice(start + 8);
pos = start + replacement.length;
} else {
pos = start + 1;
}
} else {
pos = val.length;
}
}
jsfiddle

Related

how to check first letter of every word in the string and returns next letter in the alphabet [duplicate]

I am build an autocomplete that searches off of a CouchDB View.
I need to be able to take the final character of the input string, and replace the last character with the next letter of the english alphabet. (No need for i18n here)
For Example:
Input String = "b"
startkey = "b"
endkey = "c"
OR
Input String = "foo"
startkey = "foo"
endkey = "fop"
(in case you're wondering, I'm making sure to include the option inclusive_end=false so that this extra character doesn't taint my resultset)
The Question
Is there a function natively in Javascript that can just get the next letter of the alphabet?
Or will I just need to suck it up and do my own fancy function with a base string like "abc...xyz" and indexOf()?
my_string.substring(0, my_string.length - 1)
+ String.fromCharCode(my_string.charCodeAt(my_string.length - 1) + 1)
// This will return A for Z and a for z.
function nextLetter(s){
return s.replace(/([a-zA-Z])[^a-zA-Z]*$/, function(a){
var c= a.charCodeAt(0);
switch(c){
case 90: return 'A';
case 122: return 'a';
default: return String.fromCharCode(++c);
}
});
}
A more comprehensive solution, which gets the next letter according to how MS Excel numbers it's columns... A B C ... Y Z AA AB ... AZ BA ... ZZ AAA
This works with small letters, but you can easily extend it for caps too.
getNextKey = function(key) {
if (key === 'Z' || key === 'z') {
return String.fromCharCode(key.charCodeAt() - 25) + String.fromCharCode(key.charCodeAt() - 25); // AA or aa
} else {
var lastChar = key.slice(-1);
var sub = key.slice(0, -1);
if (lastChar === 'Z' || lastChar === 'z') {
// If a string of length > 1 ends in Z/z,
// increment the string (excluding the last Z/z) recursively,
// and append A/a (depending on casing) to it
return getNextKey(sub) + String.fromCharCode(lastChar.charCodeAt() - 25);
} else {
// (take till last char) append with (increment last char)
return sub + String.fromCharCode(lastChar.charCodeAt() + 1);
}
}
return key;
};
Here is a function that does the same thing (except for upper case only, but that's easy to change) but uses slice only once and is iterative rather than recursive. In a quick benchmark, it's about 4 times faster (which is only relevant if you make really heavy use of it!).
function nextString(str) {
if (! str)
return 'A' // return 'A' if str is empty or null
let tail = ''
let i = str.length -1
let char = str[i]
// find the index of the first character from the right that is not a 'Z'
while (char === 'Z' && i > 0) {
i--
char = str[i]
tail = 'A' + tail // tail contains a string of 'A'
}
if (char === 'Z') // the string was made only of 'Z'
return 'AA' + tail
// increment the character that was not a 'Z'
return str.slice(0, i) + String.fromCharCode(char.charCodeAt(0) + 1) + tail
}
Just to explain the main part of the code that Bipul Yadav wrote (can't comment yet due to lack of reps). Without considering the loop, and just taking the char "a" as an example:
"a".charCodeAt(0) = 97...hence "a".charCodeAt(0) + 1 = 98 and String.fromCharCode(98) = "b"...so the following function for any letter will return the next letter in the alphabet:
function nextLetterInAlphabet(letter) {
if (letter == "z") {
return "a";
} else if (letter == "Z") {
return "A";
} else {
return String.fromCharCode(letter.charCodeAt(0) + 1);
}
}
var input = "Hello";
var result = ""
for(var i=0;i<input.length;i++)
{
var curr = String.fromCharCode(input.charCodeAt(i)+1);
result = result +curr;
}
console.log(result);
I understand the original question was about moving the last letter of the string forward to the next letter. But I came to this question more interested personally in changing all the letters in the string, then being able to undo that. So I took the code written by Bipul Yadav and I added some more code. The below code takes a series of letters, increments each of them to the next letter maintaining case (and enables Zz to become Aa), then rolls them back to the previous letter (and allows Aa to go back to Zz).
var inputValue = "AaZzHello";
console.log( "starting value=[" + inputValue + "]" );
var resultFromIncrementing = ""
for( var i = 0; i < inputValue.length; i++ ) {
var curr = String.fromCharCode( inputValue.charCodeAt(i) + 1 );
if( curr == "[" ) curr = "A";
if( curr == "{" ) curr = "a";
resultFromIncrementing = resultFromIncrementing + curr;
}
console.log( "resultFromIncrementing=[" + resultFromIncrementing + "]" );
inputValue = resultFromIncrementing;
var resultFromDecrementing = "";
for( var i2 = 0; i2 < inputValue.length; i2++ ) {
var curr2 = String.fromCharCode( inputValue.charCodeAt(i2) - 1 );
if( curr2 == "#" ) curr2 = "Z";
if( curr2 == "`" ) curr2 = "z";
resultFromDecrementing = resultFromDecrementing + curr2;
}
console.log( "resultFromDecrementing=[" + resultFromDecrementing + "]" );
The output of this is:
starting value=[AaZzHello]
resultFromIncrementing=[BbAaIfmmp]
resultFromDecrementing=[AaZzHello]

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'));

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*$/

Format number string using commas

I want to format numbers. I have seen some of the regex expression example to insert comma in number string. All of them check 3 digits in a row and then insert comma in number. But i want something like this:
122 as 122
1234 as 1,234
12345 as 12,345
1723456 as 17,23,456
7123456789.56742 as 7,12,34,56,789.56742
I am very new to regex expression. Please help me how to display the number as the above. I have tried the below method. This always checks for 3 digits and then add comma.
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
But i want comma every 2 digits except for the last 3 digits before the decimals as shown above.
The result will depend on your browsers locale. But this might be an acceptable solution:
(7123456789.56742).toLocaleString();
Outputs:
7,123,456,789.56742
Try it and see if it outputs 7,12,34,56,789.567421 in your locale.
Here's a function to convert a number to a european (1.000,00 - default) or USA (1,000.00) style:
function sep1000(somenum,usa){
var dec = String(somenum).split(/[.,]/)
,sep = usa ? ',' : '.'
,decsep = usa ? '.' : ',';
return dec[0]
.split('')
.reverse()
.reduce(function(prev,now,i){
return i%3 === 0 ? prev+sep+now : prev+now;}
)
.split('')
.reverse()
.join('') +
(dec[1] ? decsep+dec[1] :'')
;
}
Alternative:
function sep1000(somenum,usa){
var dec = String(somenum).split(/[.,]/)
,sep = usa ? ',' : '.'
,decsep = usa ? '.' : ',';
return xsep(dec[0],sep) + (dec[1] ? decsep+dec[1] :'');
function xsep(num,sep) {
var n = String(num).split('')
,i = -3;
while (n.length + i > 0) {
n.splice(i, 0, sep);
i -= 4;
}
return n.join('');
}
}
//usage for both functions
alert(sep1000(10002343123.034)); //=> 10.002.343.123,034
alert(sep1000(10002343123.034,true)); //=> 10,002,343,123.034
[edit based on comment] If you want to separate by 100, simply change i -= 4; to i -= 3;
function sep100(somenum,usa){
var dec = String(somenum).split(/[.,]/)
,sep = usa ? ',' : '.'
,decsep = usa ? '.' : ',';
return xsep(dec[0],sep) + (dec[1] ? decsep+dec[1] :'');
function xsep(num,sep) {
var n = String(num).split('')
,i = -3;
while (n.length + i > 0) {
n.splice(i, 0, sep);
i -= 3; //<== here
}
return n.join('');
}
}
use toLocaleString();
It automatically handles inserting commas and will also handle uk strings the right way
e.g.
var num=63613612837131;
alert(num.toLocaleString());
Below is the snippet of code, can be done in better way but this works :D
function formatDollar(num)
{
var p = num.toFixed(2).split(".");
var chars = p[0].split("").reverse();
var sep1000 = false;
var newstr = '';
var count = 0;
var count2=0;
for (x in chars)
{
count++;
if(count%3 == 1 && count != 1 %% !sep1000)
{
newstr = chars[x] + ',' + newstr;
sep1000=true;
}
else
{
if(!sep1000)
{
newstr = chars[x] + ',' + newstr;
}
else
{
count2++;
if(count%2 == 0 && count != 1)
{
newstr = chars[x] + ',' + newstr;
}
else
{
newstr = chars[x] + newstr;
}
}
}
}
return newstr + "." + p[1];
}

How to parse a string for having line breaking

I would like to have a function which takes 3 arguments:
sentence (string),
maxCharLen=20 (number),
separator (string)
and transform the sentence based on the parameters.
Example
var sentence = "JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions."
var newSentence = breakSentence(sentence, maxCharLen=20, separator="<br>");
newSentence // JavaScript is a prototype-based <br> scripting language that is dynamic, <br> weakly typed and has first-class functions.
P.S:
This is what I have tried:
var breakSentence = function (sentence, maxCharLen, separator)
{
sentence = sentence || "javascript is a language" ;
maxCharLen = 10 || maxCharLen; // max numb of chars for line
separator = "<br>" || separator;
var offset;
var nbBreak = sentence.length // maxCharLen;
var newSentence = "";
for (var c = 0; c < nbBreak; c += 1)
{
offset = c * maxCharLen;
newSentence += sentence.substring(offset, offset + maxCharLen) + separator;
}
return newSentence;
}
It works in this way:
breakSentence() // "javascript<br> is a lang<br>uage<br>"
it should be:
breakSentence() // "javascript<br>is a <br>language"
Here's a solution: http://snippets.dzone.com/posts/show/869
//+ Jonas Raoni Soares Silva
//# http://jsfromhell.com/string/wordwrap [v1.0]
String.prototype.wordWrap = function(m, b, c){
var i, j, l, s, r;
if(m < 1)
return this;
for(i = -1, l = (r = this.split("\n")).length; ++i < l; r[i] += s)
for(s = r[i], r[i] = ""; s.length > m; r[i] += s.slice(0, j) + ((s = s.slice(j)).length ? b : ""))
j = c == 2 || (j = s.slice(0, m + 1).match(/\S*(\s)?$/))[1] ? m : j.input.length - j[0].length
|| c == 1 && m || j.input.length + (j = s.slice(m).match(/^\S*/)).input.length;
return r.join("\n");
};
usage:
var sentence = "JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions."
sentence.wordWrap(20, "<br>",true)
// Output "JavaScript is a <br>prototype-based <br>scripting language <br>that is dynamic, <br>weakly typed and has<br> first-class <br>functions."
I would try it like that (not tested):
var breakSentence = function (sentence, maxCharLen, separator)
{
var result = "";
var index = 0;
while (sentence.length - index > maxCharLen)
{
var spaceIndex = sentence.substring(index, index + maxCharLen).lastIndexOf(' ');
if (spaceIndex < 0) //no spaces
{
alert('Don\'t know what do do with substring with one long word');
spaceIndex = maxCharLen; //assume you want to break anyway to avoid infinite loop
}
result += sentence.substring(index, index + spaceIndex + 1) + separator;
index += spaceIndex + 1;
}
return result;
}
Should break after spaces only now...
Here is my attempt to get it. It has two things you should notice:
it first removes all the separator instances (so the reordering is completely new)
it doesn't break words longer then maxCharLen characters.
It worked in node 0.6.10
var breakSentence = function (sentence, maxCharLen, separator) {
var words = [] // array of words
, i // iterator
, len // loop
, current = '' // current line
, lines = [] // lines split
;
sentence = sentence || "javascript is a language";
maxCharLen = 10 || maxCharLen;
separator = separator || "<br>";
sentence = sentence.replace(separator, '');
if (sentence.length < maxCharLen) return [sentence]; // no need to work if we're already within limits
words = sentence.split(' ');
for (i = 0, len = words.length; i < len; i += 1) {
// lets see how we add the next word. if the current line is blank, just add it and move on.
if (current == '') {
current += words[i];
// if it's not like that, we need to see if the next word fits the current line
} else if (current.length + words[i].length <= maxCharLen) { // if the equal part takes the space into consideration
current += ' ' + words[i];
// if the next word doesn't fit, start on the next line.
} else {
lines.push(current);
current = words[i];
// have to check if this is the last word
if (i === len -1) {
lines.push(current);
}
}
}
// now assemble the result and return it.
sentence = '';
for (i = 0, len = lines.length; i < len; i += 1) {
sentence += lines[i];
// add separator if not the last line
if (i < len -1) {
sentence += separator;
}
}
return sentence;
}

Categories

Resources