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,""));
Related
The initial string:
initString = '/digital/collection/music/bunch/of/other/stuff'
What I want: music
Specifically, I want any term (will never include slashes) that would come between collection/ and /bunch
How I'm going about it:
if(initString.includes('/digital/collection/')){
let slicedString = initString.slice(19); //results in 'music/bunch/of/other/stuff'
let indexOfSlash = slicedString.indexOf('/'); //results, in this case, to 5
let desiredString = slicedString.slice(0, indexOfSlash); //results in 'music'
}
Question:
How the heck do I accomplish this in javascript in a more elegant way?
I looked for something like an endIndexOf() that would replace my hardcoded .slice(19)
lastIndexOf() isn't what I'm looking for, because I want the index at the end of the first instance of my substring /digital/collection/
I'm looking to keep the number of lines down, and I couldn't find anything like a .getStringBetween('beginCutoff, endCutoff')
Thank you in advance!
your title says "index" but your example shows you wanting to return a string. If, in fact, you are wanting to return the string, try this:
if(initString.includes('/digital/collection/')) {
var components = initString.split('/');
return components[3];
}
If the path is always the same, and the field you want is the after the third /, then you can use split.
var initString = '/digital/collection/music/bunch/of/other/stuff';
var collection = initString.split("/")[2]; // third index
In the real world, you will want to check if the index exists first before using it.
var collections = initString.split("/");
var collection = "";
if (collections.length > 2) {
collection = collections[2];
}
You can use const desiredString = initString.slice(19, 24); if its always music you are looking for.
If you need to find the next path param that comes after '/digital/collection/' regardless where '/digital/collection/' lies in the path
first use split to get an path array
then use find to return the element whose 2 prior elements are digital and collection respectively
const initString = '/digital/collection/music/bunch/of/other/stuff'
const pathArray = initString.split('/')
const path = pathArray.length >= 3
? pathArray.find((elm, index)=> pathArray[index-2] === 'digital' && pathArray[index-1] === 'collection')
: 'path is too short'
console.log(path)
Think about this logically: the "end index" is just the "start index" plus the length of the substring, right? So... do that :)
const sub = '/digital/collection/';
const startIndex = initString.indexOf(sub);
if (startIndex >= 0) {
let desiredString = initString.substring(startIndex + sub.length);
}
That'll give you from the end of the substring to the end of the full string; you can always split at / and take index 0 to get just the first directory name form what remains.
You can also use regular expression for the purpose.
const initString = '/digital/collection/music/bunch/of/other/stuff';
const result = initString.match(/\/digital\/collection\/([a-zA-Z]+)\//)[1];
console.log(result);
The console output is:
music
If you know the initial string, and you have the part before the string you seek, then the following snippet returns you the string you seek. You need not calculate indices, or anything like that.
// getting the last index of searchString
// we should get: music
const initString = '/digital/collection/music/bunch/of/other/stuff'
const firstPart = '/digital/collection/'
const lastIndexOf = (s1, s2) => {
return s1.replace(s2, '').split('/')[0]
}
console.log(lastIndexOf(initString, firstPart))
I have a Angular 2 / Typescript application string that contains number representations such as the following...
10000
10000.50
-10000
-10000.50
0
I want to add in commas after the thousand mark, for example...
10,000
10,000.50
-10,000
-10,000.50
0
What is the best way to do this?
I have tried some other answers but nothing is quite right.
For example this.value.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"); and this.value.toLocaleString(); don't seem to handle both the comman and decimal point.
Have you tried
var some_string_value = '-10000.50';
parseFloat(some_string_value).toLocaleString()
?
Use "indexOf('.')",splice to two part,then use the method you found.
function addComma(num){
//some type check here
var numStr = num.toString();
var intEnd = numStr.indexOf('.');
var onePart =numStr,otherPart ='';
if(intEnd !== -1){
var onePart = numStr.slice(0,intEnd);
var otherPart = numStr.slice(intEnd);
}
return onePart.replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')+otherPart;
}
You can use a pipe, you can find a full answer to your question here: Add Comma Separated Thousands to Number Inputs in Angular2
I am adding a users input in to UI as they add numbers and returning the results. The input is currency so I need to carry it out two decimals and not round.
Here is an example of my code:
function ceiling2(number) {
var ceiling2;
return ceiling2 = Math.ceil(number*100)/100;
}
//Totals
function lD23Total (e){
var app = UiApp.getActiveApplication();
var tB1v = parseInt(e.parameter.TextBox1);
var tB9v = parseInt(e.parameter.TextBox9);
var tB17v = parseInt(e.parameter.TextBox17);
var tB25v = parseInt(e.parameter.TextBox25);
var tB33v = parseInt(e.parameter.TextBox33);
var tB41v = parseInt(e.parameter.TextBox41);
var tB49v = parseInt(e.parameter.TextBox49);
var lD23 = app.getElementById("LabelD23").setStyleAttribute('fontWeight','bold');
var lD23T = tB1v + tB9v + tB17v + tB25v + tB33v + tB41v + tB49v;
lD23.setText("$ " + ceiling2(lD23T));
var app = UiApp.getActiveApplication();
app.close();
return app;
}
Currently it returns a rounded number.
I appreciate an suggestions you may offer!
Jon
The function parseInt() will convert the value to an integer, dropping the values after the decimal. Use parseFloat() instead.
I think your function is just fine...
if you remove the parseInt() and replace it either with parseFloat()as suggested by Eric or by Number() it should work...
if not then the problem might come from the way numbers are written:
If you used 26,4567 but you should use 26.4567 with a dot as separator in place of a comma.
Could you try and keep us informed ?
regards,
Serge
Or you can use this before sending to your function:
var newnumber=Number(number.toString().replace(",","."));// convert to string, replace comma with dot and set as number again.
and your function will work in both cases
I have seen plenty of code snippets to force a <Textarea> to have only X number of characters and then not allow anymore. What I am in need of is a <Textarea> where you can specify how many characters I can have at one time at most. Almost like a max buffer size. Think of it like a rolling log file. I want to always show the last/newest X number of characters.
Simpler the solution the better. I am not a web expert so the more complicated it gets the more greek it looks to me. :)
I am already using jQuery so a solution with that should be ok.
try this:
<textarea id="yourTextArea" data-maxchars="1000"></textarea>
var textarea = document.getElementById('yourTextArea');
var taChanged = function(e){
var ta = e.target;
var maxChars = ta.getAttribute('data-maxchars');
if(ta.value.length > maxChars){
ta.value = ta.value.substr(0,maxChars);
}
}
textarea.addEventListener('change', taChanged, 1);
for the last chars:
ta.value = ta.value.substr(ta.value.length - 1000);
And jQuery implementation:
$('#text').keyup(function() {
var max = $(this).data('maxchars'),
len = $(this).val().length;
len > max && $(this).val(function() {
return $(this).val().substr(len - max);
});
});
http://jsfiddle.net/WsnSk/
No code, I can't even spell JavaScript, but basically as you're about to add new text, check the length of the existing text. If the old text plus the new text is too long, trim off the beginning of the old text (likely at a newline or whatever). Rinse and repeat.
Here is the working code on Fiddle. It uses Jquery to make it simple.
<textarea id="txtArea"></textarea>
var size = 5;
$('#txtArea').change(function(){
var strValue = $('#txtArea').val();
strValue = strValue.split("").reverse().join("").substring(0, size).split("").reverse().join("");
alert(strValue);
});
I can not find the solution. I've tried to assume that count of \n symbols is the same with lines count, but sometimes this method works incorrectly (e.g. after paste text from clipboard)
i've tried different jQuery plugins, but still unsuccessfully.
any idea?
Why not just do this:
Take the text content only up to selectionStart then make it an array by splitting at eol
p = $('#Form_config').val().substr(0, $('#Form_config')[0].selectionStart).split("\n");
// line is the number of lines
line = p.length;
// col is the length of the last line
col = p[p.length-1].length;
Try to use this:
var pos = getCaretPos(document.formName.textareaName);
function getCaretPos(obj)
{
obj.focus();
if(obj.selectionStart) return obj.selectionStart;//Gecko
else if (document.selection)//IE
{
var sel = document.selection.createRange();
var clone = sel.duplicate();
sel.collapse(true);
clone.moveToElementText(obj);
clone.setEndPoint('EndToEnd', sel);
return clone.text.length;
}
return 0;
}
The descision is not so simple and requieres large amount of javascript code. So, finally i've used CodeMirror Project by Marijn Haverbeke (https://github.com/marijnh/CodeMirror)