I'm writing a JavaScript function that has to take in a string argument & determine the word or words with the maximum number or repeated (or most frequent) non sequential characters and return that word or words.
The way that I went about solving this problem was to first find the maximum number of times a character was repeated per word and record that number to use later in a function to test against every word in the string (or the array of strings as I later split it); if the word met the conditions, it's pushed into an array that I return.
My maxCount function seemed to work fine on its own but when I try to make it work together with my other function to get the words with max repeated chars returned, it's not working in JS Fiddle - it keeps telling me that "string.split is not a function" - I'll admit that the way I'm using it (string.split(string[i]).length) to analyze words in the string letter by letter is a bit unconventional - I hope there's some way to salvage some of my logic to make this work in the functions that can work together to get the results that I want.
Also, I don't know if I'm using Math.max correctly/in a "legal" way, I hope so. I've tried switching my variable name to "string" thinking that would make a difference but it did not even though my arguments are of the string variety and it's a string that's being represented.
Here's a link to my Fiddle:
https://jsfiddle.net/Tamara6666/rdwxqoh6/
Here's my code:
var maxCount = function (word) {
/// var maxRepeats = 0;
var numArray = [];
var string = word;
for (var i = 0, len = string.length; i < len; i++) {
//split the word('string') into letters at the index of i
numArray.push((string.split(string[i]).length) -1);
}
var max = Math.max(...numArray);
return max;
}
///console.log(maxCount("xxxxxxxxxxxxx"));
var LetterCount = function(string){
var repeatedChars = 0;
var wordArray=[];
var stringArray = string.split(" ");
for (var i = 0; i < stringArray.length; i++){
var eachWord = stringArray[i];
var maxRepeats = maxCount(stringArray);
if (repeatedChars < maxRepeats) {
repeatedChars = maxRepeats;
wordArray = [eachWord];
}else if (repeatedChars == maxRepeats) {
wordArray.push(eachWord);
}
}
return wordArray;
};
console.log(LetterCount("I attribute my success to cats"));
//should return ["attribute", "success"]
*** I've tried to map this first function onto the array formed when I split my string at the spaces but it is just returned me an empty array (I also might not have been using map correctly in this example); I also have tried using valueOf to extract the primitive value out of the array from the first function which also didn't work. I'm not really sure what to do at this point or what angle to take- I feel if I understood more what was going wrong I could more easily go about fixing it. Any help would be much appreciated. Thanks!
You are passing an array to maxCount at line 20, while it expects a string:
var maxRepeats = maxCount(stringArray);
You should use:
var maxRepeats = maxCount(eachWord);
If you are getting split is not a function error then first make sure that your string isn't null by printing it on console. If it isn't null then confirm that its a string not an array or some other thing.
I have a number say 2,500.00 and i want to convert the number into 2.500,00. So, we can replace the special character using replace like
var x = 2,500.00;
x.replace(/,/g,".");
and for "Dot" also, we can do it. But in this case, it won't work because when we apply replace function for comma as above, the number will become 2.500.00 and if we apply now, it will become as 2,500,00.
So is there any way to convert 2,500.00 into 2.500,00 ?
String.prototype.replace can take a function:
'2,123,500.00'.replace(/[,.]/g, function(c){ return c===',' ? '.' : ','; });
You can use:
var x = '2,123,500.00';
var arr = x.split('.');
var y = arr[0].replace(/,/g, '.') + ',' + arr[1];
//=> 2.123.500,00
You're in luck, .replace() accept a function as second argument. That function has the matched string as argument and the returned value will be the replace_by value of .replace().
In short, you can simply check what the matched string is and return the right value :
var str = "2,500.00";
var changed_str = str.replace(/,|\./g, function(old){
if (old === '.')
return ',';
else if (old === ',')
return '.';
});
document.write(changed_str)
Why not use the built-in methods to format your numbers correctly?
Number.toLocaleString() would work just fine here.
If you actually have a number as you said, you can easily achieve this using the right locale. If you have a String representation of your number, you would first have to parse it.
This (now) works for any number of commas or dots, even if trailing or leading dots or commas.
HTML:
<div id="result"></div>
JS:
var x = '.,2.123,50.0.00.';
var between_dots = x.split('.');
for (var i = 0; i < between_dots.length; i++) {
between_dots[i] = between_dots[i].replace(/,/g, '.');
}
var y = between_dots.join(',');
document.getElementById('result').innerHTML = y;
Here's the JSFiddle
I am trying to replace all double commas with ,null,
The problem is that i need to keep doing it while it is replacing it. I am thinking about adding a loop but is there any other more eficient alternative?
var test = "[1,2,,,3,4,,,,,,5,6]".replace(/,{2}/g, ",null,");
alert(test);
The result should be:
"[1,2,null,null,3,4,null,null,null,null,null,5,6]"
But is instead:
[1,2,null,,3,4,null,,null,,null,5,6]
So I would have to create a loop and do it until all double commas are done. Not sure if there is any other way?
As a side info, this is so that I can afterwards do:
var myArray = $.parseJSON(test);
Which currently it fails which I'm guessing that it's because it is not valid json.
Single regex:
"[AB,,,CD,,,,,,EF]".replace(/,(?=,)/g, ',null');
demo
Here we use the ?= lookahead to find 2 commas ("comma with a comma after it") but match and replace only the first.
Edit:
You seem to be interested in speed, here are some tests.
str.split(',').map(function(x) { return x ? x : 'null' }).join(',');
FIDDLE
splits the string by commas, then map() iterates and returns each value from the callback, and the ternary returns x (the value) if thruthy and the string 'null' if falsy, which an empty string is, then join it back together again.
You can do this:
var test = "[1,2,,,3,4,,,,,,5,6]".split(',').join(',|').replace(/\|,/g,"null,");
alert(test.replace(/\|/g,""));
It alerts:
[1,2,null,null,3,4,null,null,null,null,null,5,6]
Demo: http://jsfiddle.net/AmitJoki/Zuv38/
Not sure if regex could handle that without looping.
Alternative solution is to split is into an array: '1,2,,,3,4,,,,,,5,6'.split(','); and then loop through it and replace all empty strings with null and then join it back.
So, something like this:
var s = '1,2,,,3,4,,,,,,5,6';
var a = s.split(',');
for (var i = 0; i < a.length; i++) {
if (a[i] == "") {
a[i] = "null";
}
}
s = '[' + a.join(',') + ']';
See it here: http://jsfiddle.net/fVMLv/1/
Try this
var str = "1,2,,,3,4,,,,,,5,6";
str = str.split(',');
var strResult ='';
$(str).each(function(){
if(this==''){
strResult +='null,';
}
else{
strResult +=this+',';
}
});
strResult = strResult.substring(0,strResult.length-1);
alert(strResult);
DEMO
The problem is with the double commas occurring consecutively.
,,,, -> will be taken as 2 sets of double commas by that RegExp. So, result will be:-
,null,,null, -> note that the occurrence of another double comma in between is skipped, since the RegEx is greedy (2nd comma is already used, which is not used again together with 3rd comma. rather 3rd and 4th are used together).
var test = "[AB,,,CD,,,,,,EF]".replace(/,,/g, ",null,").replace(/,,/g, ",null,");
alert(test);
So, with this RegExp, calling it twice will fix this.
I asked a similar question yesterday .. If I have for example 0-9999 , how can I turn this into 09999 , basically removing the - and make it an integer in javascript ?
var = 0-9999
turn that into 9999 integer
or var = 2-9999 , turn that into 29999
Thanks a bunch
This should do the trick:
num = num.replace(/[^0-9]+/g, '') * 1;
It'll strip out any non-numeric characters and convert the variable into an integer. Here's a jsFiddle demonstration for you.
The most obvious and basic of solutions would be:
var s = "1-2345";
var t = s.replace("-","");
var i = parseInt(t,10);
But that's making a lot of assumptions and ignoring any errors.
Try this:
var i = '0-9999';
var int = Number(i.replace('-', ''));
window.alert(int);
Note in Firefox, parseInt() won't work with leading zeros unless you pass in a radix (this appears to be a bug):
var int = parseInt(i.replace('-', ''), 10);
Fiddler
Remember that
var x = 2-9999
is the same as
var x = -9997
because the dash is seen as a subtraction symbol unless you use quotation marks (Single or double, doesn't matter).
So, assuming that you properly quote the text, you can use the following function to always pull out a character that is in any given spot of the text (Using a zero-based index).
function extractChar(myString,locationOfChar){
var y = myString.substring(0,locationOfChar-1)
var z = myString.substring(locationOfChar+1)
var s = y.concat(z)
var i = parseInt(s,10)
return i
}
therefore
var i = extractChar("2-9999",1)
Will be the same as
var i = 29999
I have one string which contain number and character. I need to separate number and character. I have don't have a delimiter in between. How can I do this.
Var selectedRow = "E0";
I need to "0" in another variable.
Help me on this.
Depends on the format of the selected row, if it is always the format 1char1number (E0,E1....E34) then you can do:
var row = "E0";
var rowChar = row.substring(0, 1);
// Number var is string format, use parseInt() if you need to do any maths on it
var number = row.substring(1, row.length);
//var number = parseInt(row.substring(1, row.length));
If however you can have more than 1 character, for example (E0,E34,EC5,EDD123) then you can use regular expressions to match the numeric and alpha parts of the string, or loop each character in the string.
var m = /\D+(\d+)/gi.exec(selectedRow);
var row = m.length == 2 ? m[1] : -1;
selectedRow.charAt(1)
Becomes more complex if your example is something longer than 'E0', obviously.