I have posted a few days ago a question about a challenge that I did on jshero.net:
The link for the question is [here]
I feel like I am close, the best answer I could come up with is:
function list(arr){
let myL= arr.slice(0,2);
let myLi= myL.join(' , ')
let myL2 = arr.slice(2,3);
let myLi2= myL2.join(' and ');
let myList = myLi + myLi2
if (arr.length <=2){
return arr.join(' and ')} else {
return myList}
}
list(['Huey', 'Dewey', 'Louie'])
Now if I use this code it will return 'Huey , DeweyLouie'. Do you have any idea on how to get the right answer?
Just slice to the last element, and then append last element. Add a few checks for edge cases.
Seems like a really trivial problem. Not sure why all the overly complicated solutions. Am I misunderstanding the problem?
list = l => l.length > 1 ? l.slice(0,-1).join(', ') + ` and ${l.pop()}` : l[0]||''
console.log(
list(['Huey','Dewey','Louie'])
)
console.log(
list(['Huey','Dewey'])
)
console.log(
list(['Huey'])
)
Related
I receive a set of functions in text for another software program which I need to modify and then save and am trying to find the best way to do this.
I could receive a text like this:
Sum(Revenue) + Sum({<CostCentre={'$(=Sum(FIELD))'}>}COGS)
I would like to be able to add text directly after Sum( where it is NOT immediately followed by {< Ideally my end result would like this:
Sum(TEXT_I_WANT_TO_ADD Revenue) + Sum({<CostCentre={'$(=Sum(TEXT_I_WANT_TO_ADD FIELD))'}>}COGS)
Any ideas how to achieve this in a simple way? So far my only idea was to use split and then look at the next object of the array to determine if it contains {<, however I am wondering if there is an easier way to do this.
My try (which works and but is hard to follow and not sure if it will always work):
let text = `Sum(Revenue) + Sum({<CostCentre={'$(=Sum(FIELD))'}>}COGS)`;
let input_text = 'TEXT_I_WANT_TO_ADD ';
let split_text = 'Sum('
let split = text.split(split_text);
console.log(split);
let final_text = '';
for (let i in split) {
let split_modified;
// Not last item
if (i < split.length - 1) {
let next = (parseInt(i) + parseInt(1));
// Does not include {<
console.log(next, split[next]);
if (!split[next].includes('{<')) {
final_text += split_text + input_text;
}
// Does include {<
else {
final_text += split_text + split[next]
}
}
// Last item
else {
final_text += split[i]
}
}
console.log(final_text);
Any ideas how to do this is a better, easier way?
You can capture the word inside the parenthesis of Sum() and replace it :
const input_text = "TEXT_I_WANT_TO_ADD ";
const text = `Sum(Revenue) + Sum({<CostCentre={'$(=Sum(FIELD))'}>}COGS)`;
const result = text.replace(/Sum\(\w+\)/g, match => `Sum(${input_text})`);
console.log(result);
Hello I am working on a project and last night I had a thought that would make a lot of what I am wanting to do a heck of a lot easier, the only problem is I am not sure on the best way to tackle it. Let me explain....
I have a form on a website where a user enters a VIP ID that is in a pre-determined format and follows a logical naming convention.
Example: app.prod.platform.org.dc1.prod.site.com-HTTP_80tcp-00000000-lb
I want to pull out the following information from the entered text.
prod.platform.org.
Then I want to reverse it logically
.org.platform.prod
And then I want to replace the “.” For “/”
/org/platform/prod
And finally I want to add a postfix of “/open*”
/org/platform/prod/open*
So in short,
INPUT = app.prod.platform.org.dc1.prod.site.com-HTTP_80tcp-00000000-lb
OUTPUT = /org/platform/prod/open*
I am using javascript/jquery for everything else but I am pretty new to all of this so I tend not to know the best route to tackle a problem. If I need to provide some more detail I can do. Any help is much appreciated.
Or simple like this
var input = "app.prod.platform.org.dc1.prod.site.com-HTTP_80tcp-00000000-lb" ;
var output =
"/" +
input
.split(".")
.slice(1, 4)
.reverse()
.join("/") +
"/open";
var output =
"/" +
"app.prod.platform.org.dc1.prod.site.com-HTTP_80tcp-00000000-lb"
.split(".")
.slice(1, 4)
.reverse()
.join("/") +
"/open";
You can try below code :
var input = "app.prod.platform.org.dc1.prod.site.com-HTTP_80tcp-00000000-lb";
var tempArr = input.split(".");
var newArr = new Array();
for(var i=1;i<tempArr.length;i++){
if(tempArr[i]=="org" || tempArr[i]=="net"){
newArr.push(tempArr[i]);
break;
}
newArr.push(tempArr[i]);
}
newArr.reverse();
var output="/"+newArr.join("/")+"/open*";
Bear with me, I'm still kinda new to javascript.. I am trying to sort a list of save-game codes to be sorted by their first parse of the element.
var vList =["1|846|Doc|2|0|false|", "11|203|Derik|7|3|false|", "21|670|Mike|5|5|true|", "13|11|Ron|0|0|false|", "9|1000|Blood|9|9|true|"];
var vParse;
for (i = 0; i < (vParse.length); i++)
var vParse[i]= vList.split('|');
// then somehow sort all the data based on vParse[0]?
I tried a few sorting submissions from other folks, but I couldn't get it to ignore all the font after the first parse. Could anyone help me please?
You can use Array.sort and just split on the pipe, get the first item, and when subtracting the strings are converted to numbers anyway
var vList =["1|846|Doc|2|0|false|", "11|203|Derik|7|3|false|", "21|670|Mike|5|5|true|", "13|11|Ron|0|0|false|", "9|1000|Blood|9|9|true|"];
vList.sort(function(a,b) {
return a.split('|')[0] - b.split('|')[0];
});
console.log(vList)
Try some like that:
vList.sort( function( a, b ) {
return parseInt( a.split( '|' )[ 0 ] ) - parseInt( b.split( '|' )[ 0 ] );
} );
You can read more about sort, split and parseInt methods.
How about this
vList.map(function(el){return {sortBy : parseInt(el.split('|')[0]), original : el}}).sort(function(a,b){return a.sortBy - b.sortBy}).map(function(el){return el.original})
)
I have searched high and low, but i can´t find what i need. Or i´m to stupid to get it right ;-)
I need a page with several input boxes where i can type some text, and then an output area below each input, that shows the text converted to some predefined numbers.
example:
input: abcde fghi æøå (i need all kinds of characters like .,/: etc.)
output: 064 065 066 067 068 032
So it needs to convert like this:
"a"="064 "
"b"="065 "
"space"="032 "
(and yes, each number in output needs to be separated, or a space added after each number)
I have tried some different cipher guides in both php and javascript, but can´t get it to work. I did do an Excel document that could do some of it, but it had a limited amount of characters it could convert, then it started behaving weird. So i thought maybe PHP was the answer!
Any help is very appreciated
/Rasmus
In the spirit of elclanrs deleted answer, and for posterity:
<script>
// Using standard for loop
function stringToCharcodes(s) {
var result = [];
function pad(n){ return (n<10? '00' : n<100? '0' : 0) + n;}
for (var i=0, iLen=s.length; i<iLen; i++) {
result.push(pad(s.charCodeAt(i)));
}
return result.join(' ');
}
// Using ES5 forEach
function stringToCharcodes2(s) {
var result = [];
function pad(n){ return (n<10? '00' : n<100? '0' : 0) + n;}
s.split('').forEach(function(a){result.push(pad(a.charCodeAt(0)))});
return result.join(' ');
}
</script>
<input onkeyup="document.getElementById('s0').innerHTML = stringToCharcodes(this.value);"><br>
<span id="s0"></span>
Edit
If you want a custom mapping, use an object (I've only included 2 characters, you can add as many as you want):
var mapChars = (function() {
var mapping = {'198':'019', '230':'018'};
return function (s) {
var c, result = [];
for (var i=0, iLen=s.length; i<iLen; i++) {
c = s.charCodeAt(i);
result.push(c in mapping? mapping[c] : c);
}
return result.join(' ');
}
}());
alert(mapChars('Ææ')); //
Using the character code for mapping seems to be a reasonable solution, using the actual character may be subject to different page character encoding.
Sir,
I was doing a project with javascript .I want to replace a text with regex.in a paragraph i want to replace some word using javascript
eg:
var str =" Would you like to have responses to your questions |code Would you like to have responses to your questions code| Would you like to have responses to your questions "
var n=str.replace("to","2");
Here all the "to" will be replaced.We don't want to remove between |code to code| Please help me any one.....
I think you shouldn't rely on regexps for these kind of tasks, since it would be overcomplicated and therefore slow. Anyway, if your expression is correct (i.e., for every "|code" there's a "code|" and there aren't nested code tags), you can try this:
var n = str.replace(/to(?!(?:\|(?!code)|[^\|])*code\|)/g, "2");
Not only it's complicated, but it's hard to maintain. The best thing to do in these cases is to split your string to chunks:
var chunks = [], i, p = 0, q = 0;
while ((p = str.indexOf("|code", p)) !== -1) {
if (q < p) chunks.push(str.substring(q, p));
q = str.indexOf("code|", p);
chunks.push(str.substring(p, p = q = q + 5));
}
if (q < str.length) chunks.push(str.substring(q));
// chunks === [" Would you like to have responses to your questions ",
// "|code Would you like to have responses to your questions code|",
// " Would you like to have responses to your questions "]
Note: str.replace("to", "2") does not replace every occurrence of "to", but only the first one.
if you want to replace all 'to' into 2 this will be the code
var str =" Would you like to have responses to your questions |code Would you like to have responses to your questions code| Would you like to have responses to your questions";
var n=str.replace(/to/g,"2");