Related
I'm starting my adventure with javascript and i got one of first tasks.
I must create function that count letter that most occur in string and write this in console.
For example:
var string = "assssssadaaaAAAasadaaab";
and in console.log should be (7,a) <---
the longest string is 7 consecutive identical characters (yes, before count i use .toLowerCase();, because the task requires it)
So far I have it and I don't know what to do next.
Someone want to help?
var string = "assssssadaaaAAAasadaaab";
var string = string.toLowerCase();
function writeInConsole(){
console.log(string);
var count = (string.match(/a/g) || []).length;
console.log(count);
}
writeInConsole();
One option could be matching all consecutive characters using (.)\1* and sort the result by character length.
Then return an array with the length of the string and the character.
Note that this will take the first longest occurrence in case of multiple characters with the same length.
function writeInConsole(s) {
var m = s.match(/(.)\1*/g);
if (m) {
var res = m.reduce(function(a, b) {
return b.length > a.length ? b : a;
})
return [res.length, res.charAt(0)];
}
return [];
}
["assssssadaaaAAAasadaaab", "a", ""].forEach(s => {
s = s.toLowerCase();
console.log(writeInConsole(s))
});
Another example when you have multiple consecutive characters with the same length
function writeInConsole(s) {
let m = s.match(/(.)\1*/g);
if (m) {
let sorted = m.sort((a, b) => b.length - a.length)
let maxLength = sorted[0].length;
let result = [];
for (let i = 0; i < sorted.length; i++) {
if (sorted[i].length === maxLength) {
result.push([maxLength, sorted[i].charAt(0)]);
continue;
}
break;
}
return result;
}
return [];
}
[
"assssssadaaaAAAasadaaab",
"aaabccc",
"abc",
"yyzzz",
"aa",
""
].forEach(s => {
s = s.toLowerCase();
console.log(writeInConsole(s))
});
I'm no sure if this works for you:
string source = "/once/upon/a/time/";
int count = 0;
foreach (char c in source)
if (c == '/') count++;
The answer given by using regular expressions is more succinct, but since you say you are just starting out with programming, I will offer a verbose one that might be easier to follow.
var string = "assssssadaaaAAAasadaaab";
var string = string.toLowerCase();
function computeLongestRun(s) {
// we set up for the computation at the first character in the string
var longestRunLetter = currentLetter = string[0]
var longestRunLength = currentRunLength = 1
// loop through the string considering one character at a time
for (i = 1; i < s.length; i++) {
if (s[i] == currentLetter) { // is this letter the same as the last one?
currentRunLength++ // if yes, reflect that
} else { // otherwise, check if the current run
// is the longest
if (currentRunLength > longestRunLength) {
longestRunLetter = currentLetter
longestRunLength = currentRunLength
}
// reset to start counting a new run
currentRunLength = 1
currentLetter = s[i]
}
}
return [longestRunLetter, longestRunLength]
}
console.log(computeLongestRun(string))
I want to find element from 3 arrays and create string using values. I have tried and given the output. But I want to know that, is there any better solution for this.
var numbers = ['1','2','3','4','5'];
var letters = ['A','B','C','D','E'];
var romans = ['I','II','III','IV','V'];
function findInArray(input){
var index = -1;
if(numbers.indexOf(input) >= 0){
index = numbers.indexOf(input);
} else if(letters.indexOf(input) >= 0){
index = letters.indexOf(input);
} else if(romans.indexOf(input) >= 0){
index = romans.indexOf(input);
}
if(index > -1){
var data = '{"numbers":"'+numbers[index]+'","letters":"'+letters[index]+'","romans":"'+romans[index]+'"}';
console.log(data);
}
}
findInArray('2');
output : {"numbers":"2","letters":"B","romans":"II"}
You don't need to check if indexOf exists for each of the arrays. You can just find the max value of index for all the three arrays.
If the argument exists in any of the array, it will return a positive values (which results in true)
Then you can simply return the concatenation of the result using the template strings
var numbers = ['1','2','3','4','5'];
var letters = ['A','B','C','D','E'];
var romans = ['I','II','III','IV','V'];
var findInArray = (i) => {
var index = Math.max(numbers.indexOf(i), letters.indexOf(i), romans.indexOf(i));
if (index) {
return `{numbers: ${numbers[index]}, letters: ${letters[index]}, romans: ${romans[index]}}`;
}
}
console.log(findInArray('2'));
console.log(findInArray('D'));
console.log(findInArray('V'));
Vishal,
#Jonas has used a self executing function.
For example it will output 25
(function(x){
return x*x;
}(5));
here 5is the parameter of this self executing function which will output to 25
Back to answer; When you convert his answer to raw it will look something like
const findInArray = val => (i => ({ //i = 1 here
numbers: numbers[1],
letters: letters[1],
romans: romans[1]
}))(Math.max(1,-1,-1) //will output 1);
Hope it makes sense.
resource - http://markdalgleish.com/2011/03/self-executing-anonymous-functions/
Might be simpler with:
const findInArray = val => (i => ({
numbers: numbers[i],
letters: letters[i],
romans: romans[i]
}))(Math.max(
numbers.indexOf(val),
letters.indexOf(val),
romans.indexOf(val)
));
I have a string with certain amount of commas. I want to find index of 5-th comma and then splice it. How can I do it?
Like this string: "This, is, my, javascript, string, to, present"
Turn into this: "This, is, my, javascript, string to, present"
var str = "This, is, my, javascript, string, to, present";
var i = 0, c = 5; // for flexibility c could be any number (3 for the third, ...)
while((i = str.indexOf(',', i + 1)) !== -1 && --c) // look for the fifth comma if any
;
if(i != -1) // if there is a fifth comma
str = str.substr(0, i) + str.substr(i + 1); // then remove it
console.log(str);
You could splice the array after slitting the string.
var string = 'This, is, my, javascript, string, to, present',
pos = 5,
temp = string.split(',');
temp.splice(pos -1, 0, temp.splice(pos - 1, 2).join(''));
console.log(temp.join(','));
1) The solution using String.prototype.replace() function:
var str = "This, is, my, javascript, string, to, present",
count = 0;
spliced = str.replace(/,/g, function(m){
return (++count == 5)? '' : m;
});
console.log(spliced);
2) The alternative solution using String.prototype.split() and Array.prototype.slice() functions:
var str = "This, is, my, javascript, string, to, present",
parts = str.split(','),
spliced = (parts.length > 5)? parts.slice(0, 5).join(',') + parts.slice(5).join(',') : parts.join(',');
console.log(spliced);
Try this;
function removeCharacterAtIndex(value, index) {
return value.substring(0, index) + value.substring(index + 1);
}
var input = "This, is, my, javascript, string, to, present";
console.log(removeCharacterAtIndex(input, 32));
var myStringArray = myString.split("");
var count = 0;
myStringArray.forEach(function(item, index){
if(item === ','){
count ++;
}
if (count ===5){
indexOf5thcomma = index;
}
});
myStringArray.splice(indexOf5thcomma, 1);
myString = myStringArray.join("");
Try something like this?
function getPosition(string, subString, index) {
return string.split(subString, index).join(subString).length;
}
Usage:
var myString = "This, is, my, javascript, string, to, present";
getPosition(myString, ',', 5);
Use some tricks on String.prototype.replace:
function replace (str, word, pos) {
let cnt = 0
return str.replace(word, word => ++cnt == pos ? '' : word)
}
console.log(replace("This, is, my, javascript, string, to, present", ',', 5)
The second argument of String.prototype.replace can be a function, which receives a matched string and returns the string to be place into the position. So we can use a scoped counter to determine which comma is to be removed.
Try like this:
var myString = "This, is, my, javascript, string, to, present";
var counter = 0;
myString = myString.split(""); // string to array
// find and replace 5th comma in array using counter
for (var i = 0; i < myString.length; i++) {
if (myString[i] === ",") {
counter++;
if (counter === 5) {
myString.splice(i, 1);
}
}
}
myString = myString.join(""); // array to string
I have a JavaScript string sentrptg2c#appqueue#sentrptg2c#vwemployees#.
I want to get last string vwemployees through RegExp or from any JavaScript function.
Please suggest a way to do this in JavaScript.
You can use the split function:
var str = "sentrptg2c#appqueue#sentrptg2c#vwemployees#";
str = str.split("#");
str = str[str.length-2];
alert(str);
// Output: vwemployees
The reason for -2 is because of the trailing #. If there was no trailing #, it would be -1.
Here's a JSFiddle.
var s = "...#value#";
var re = /#([^#]+)#^/;
var answer = re.match(s)[1] || null;
if you're sure the string will be separated by "#" then you can split on # and take the last entry... I'm stripping off the last #, if it's there, before splitting the string.
var initialString = "sentrptg2c#appqueue#sentrptg2c#vwemployees#"
var parts = initialString.replace(/\#$/,"").split("#"); //this produces an array
if(parts.length > 0){
var result = parts[parts.length-1];
}
Try something like this:
String.prototype.between = function(prefix, suffix) {
s = this;
var i = s.indexOf(prefix);
if (i >= 0) {
s = s.substring(i + prefix.length);
}
else {
return '';
}
if (suffix) {
i = s.indexOf(suffix);
if (i >= 0) {
s = s.substring(0, i);
}
else {
return '';
}
}
return s;
}
No magic numbers:
var str = "sentrptg2c#appqueue#sentrptg2c#vwemployees#";
var ar = [];
ar = str.split('#');
ar.pop();
var o = ar.pop();
alert(o);
jsfiddle example
I have this string:
0000000020C90037:TEMP:data
I need this string:
TEMP:data.
With PHP I would do this:
$str = '0000000020C90037:TEMP:data';
$arr = explode(':', $str);
$var = $arr[1].':'.$arr[2];
How do I effectively explode a string in JavaScript the way it works in PHP?
This is a direct conversion from your PHP code:
//Loading the variable
var mystr = '0000000020C90037:TEMP:data';
//Splitting it with : as the separator
var myarr = mystr.split(":");
//Then read the values from the array where 0 is the first
//Since we skipped the first element in the array, we start at 1
var myvar = myarr[1] + ":" + myarr[2];
// Show the resulting value
console.log(myvar);
// 'TEMP:data'
String.prototype.explode = function (separator, limit)
{
const array = this.split(separator);
if (limit !== undefined && array.length >= limit)
{
array.push(array.splice(limit - 1).join(separator));
}
return array;
};
Should mimic PHP's explode() function exactly.
'a'.explode('.', 2); // ['a']
'a.b'.explode('.', 2); // ['a', 'b']
'a.b.c'.explode('.', 2); // ['a', 'b.c']
You don't need to split. You can use indexOf and substr:
str = str.substr(str.indexOf(':')+1);
But the equivalent to explode would be split.
Looks like you want split
Try this:
arr = str.split (":");
create's an object :
// create a data object to store the information below.
var data = new Object();
// this could be a suffix of a url string.
var string = "?id=5&first=John&last=Doe";
// this will now loop through the string and pull out key value pairs seperated
// by the & character as a combined string, in addition it passes up the ? mark
var pairs = string.substring(string.indexOf('?')+1).split('&');
for(var key in pairs)
{
var value = pairs[key].split("=");
data[value[0]] = value[1];
}
// creates this object
var data = {"id":"5", "first":"John", "last":"Doe"};
// you can then access the data like this
data.id = "5";
data.first = "John";
data.last = "Doe";
Use String.split
"0000000020C90037:TEMP:data".split(':')
If you like php, take a look at php.JS - JavaScript explode
Or in normal JavaScript functionality:
`
var vInputString = "0000000020C90037:TEMP:data";
var vArray = vInputString.split(":");
var vRes = vArray[1] + ":" + vArray[2]; `
console.log(('0000000020C90037:TEMP:data').split(":").slice(1).join(':'))
outputs: TEMP:data
.split() will disassemble a string into parts
.join() reassembles the array back to a string
when you want the array without it's first item, use .slice(1)
With no intentions to critique John Hartsock, just in case the number of delimiters may vary for anyone using the given code, I would formally suggest to use this instead...
var mystr = '0000000020C90037:TEMP:data';
var myarr = mystr.split(":");
var arrlen = myarr.length;
var myvar = myarr[arrlen-2] + ":" + myarr[arrlen-1];
var str = '0000000020C90037:TEMP:data'; // str = "0000000020C90037:TEMP:data"
str = str.replace(/^[^:]+:/, ""); // str = "TEMP:data"
Just a little addition to psycho brmĀ“s answer (his version doesn't work in IE<=8).
This code is cross-browser compatible:
function explode (s, separator, limit)
{
var arr = s.split(separator);
if (limit) {
arr.push(arr.splice(limit-1, (arr.length-(limit-1))).join(separator));
}
return arr;
}
I used slice, split and join
You can just write one line of code
let arrys = (str.split(":").slice(1)).join(":");
So I know that this post is pretty old, but I figured I may as well add a function that has helped me over the years. Why not just remake the explode function using split as mentioned above? Well here it is:
function explode(str,begin,end)
{
t=str.split(begin);
t=t[1].split(end);
return t[0];
}
This function works well if you are trying to get the values between two values. For instance:
data='[value]insertdataherethatyouwanttoget[/value]';
If you were interested in getting the information from between the two [values] "tags", you could use the function like the following.
out=explode(data,'[value]','[/value]');
//Variable out would display the string: insertdataherethatyouwanttoget
But let's say you don't have those handy "tags" like the example above displayed. No matter.
out=explode(data,'insert','wanttoget');
//Now out would display the string: dataherethatyou
Wana see it in action? Click here.
var str = "helloword~this~is~me";
var exploded = str.splice(~);
the exploded variable will return array and you can access elements of the array be accessing it true exploded[nth] where nth is the index of the value you want to get
try like this,
ans = str.split (":");
And you can use two parts of the string like,
ans[0] and ans[1]
If you want to defined your own function, try this:
function explode (delimiter, string, limit) {
if (arguments.length < 2 ||
typeof delimiter === 'undefined' ||
typeof string === 'undefined') {
return null
}
if (delimiter === '' ||
delimiter === false ||
delimiter === null) {
return false
}
if (typeof delimiter === 'function' ||
typeof delimiter === 'object' ||
typeof string === 'function' ||
typeof string === 'object') {
return {
0: ''
}
}
if (delimiter === true) {
delimiter = '1'
}
// Here we go...
delimiter += ''
string += ''
var s = string.split(delimiter)
if (typeof limit === 'undefined') return s
// Support for limit
if (limit === 0) limit = 1
// Positive limit
if (limit > 0) {
if (limit >= s.length) {
return s
}
return s
.slice(0, limit - 1)
.concat([s.slice(limit - 1)
.join(delimiter)
])
}
// Negative limit
if (-limit >= s.length) {
return []
}
s.splice(s.length + limit)
return s
}
Taken from: http://locutus.io/php/strings/explode/