how do I insert dashes between each two even digits of a specific number
replace
numArr.push('-');
with
numArr.splice(i, 0, '-');
Trying to insert dashes between 2 odd numbers.Error: Illegal return statement
You could iterate from the end of the array, because you probably insert a dash and the array gets a new length.
If you start at the end, you change not the length of the items which are eligible to test and for inserting a dash.
function insertDash(string) { var array = string.split(""), i = array.length;
while (i--) { if (array[i] % 2 && array[i + 1] % 2) { array.splice(i + 1, 0, '-'); } } return array.join('');}
console.log(insertDash("99999"));console.log(insertDash("1122334455"));
Insert a hyphen between even numbers inside an array
I don't understand why everybody comes up with overcomplex (and sometimes non functional) code. It's simple task! No callbacks, regexps are needed and they don't even make the code easy to understand!
UsingArray.splice
and working with original array/** Requires array of numbers, changes THAT array, returns null
* @param numbers array of numbers
**/
function addHyphenWhenEven(numbers) {
for(var i=1, l=numbers.length;i<l; i++) {
if((numbers[i]%2 + numbers[i-1]%2) == 0) {
//Splice inserts 3rd parameter before i-th position
numbers.splice(i, 0, "-");
//Must shift the positions as the array dimensions have changed
i--;l++;
}
}
}
Using new array/** Requires array of numbers, returns new array with hyphens
* @param numbers array of numbers
* @return array with numbers and hyphens
**/
function addHyphenWhenEven2(numbers) {
if(numbers.length==0)
return [];
var result = [numbers[0]];
for(var i=1, l=numbers.length;i<l; i++) {
if((numbers[i]%2 + numbers[i-1]%2) == 0) {
result.push("-");
}
result.push(numbers[i]);
}
return result;
}
/** Requires array of numbers, changes THAT array, returns null * @param numbers array of numbers **/ function addHyphenWhenEven(numbers) { for(var i=1, l=numbers.length;i<l; i++) { if((numbers[i]%2 + numbers[i-1]%2) == 0) { //Splice inserts 3rd parameter before i-th position numbers.splice(i, 0, "-"); //Must shift the positions as the array dimensions have changed i--;l++; } } }
/** Requires array of numbers, returns new array with hyphens * @param numbers array of numbers * @return array with numbers and hyphens **/ function addHyphenWhenEven2(numbers) { if(numbers.length==0) return []; var result = [numbers[0]]; for(var i=1, l=numbers.length;i<l; i++) { if((numbers[i]%2 + numbers[i-1]%2) == 0) { result.push("-"); } result.push(numbers[i]); } return result; }var random = [];while(random.length<20){ random.push(Math.floor(Math.random()*10)); }
$("#res2")[0].innerHTML = addHyphenWhenEven2(random).join("");
addHyphenWhenEven(random);$("#res1")[0].innerHTML = random.join("");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script><h2>Using <tt>Array.splice</tt></h2><div id="res1"></div><h2>Using second array that is returned:</h2><div id="res2"></div>
Function in Javascript that inserts dashes or asterisks between each two odd or even numbers
Looping through an Array that changes its length during the loop can be very messy (i
needs to be adjusted every time you splice
). It's easier to create a new result variable:
function dashAst(para) {
const stringArray = para.toString().split('');
const numbArray = stringArray.map(Number);
let result = "";
for (let i = 0; i < numbArray.length; i++) {
const n = numbArray[i], next = numbArray[i + 1];
result += n;
if (n % 2 == next % 2) {
result += n % 2 ? '-' : '*';
}
}
return result;
}
console.log(dashAst(99946)); // "9-9-94*6"
console.log(dashAst(24877)); // "2*4*87-7"
Inserting dashes between two odd numbers
The code can be simplified a bit (as well as solve the "double char" bug):
String str = "9933444";
char[] numbers = str.toCharArray();
String result = "";
for(int i = 1; i < numbers.length; i++)
{
int value1 = Character.getNumericValue(numbers[i-1]);
int value2 = Character.getNumericValue(numbers[i]);
result += value1;
if(value1 % 2 != 0 && value2 % 2 != 0) {
result += "-";
}
}
result += numbers[numbers.length - 1];
System.out.println(result);
OUTPUT
9-9-3-3444
The reason for the "double char" bug is that every loop prints both the items on the places i-1
and i
. which means that i
will be printed again on the next loop (where it will become i-1
).
In case you're using Java 8 - you can use a Stream
do something that looks more like what you were originally trying to do:
public static void main(String[] args){
String str = "9933444";
List<String> lst = Arrays.asList(str.split(""));
String res = lst.stream().reduce((a,b) -> {
if (isOdd(a) && isOdd(b)) {
return a + "-" + b;
}
else {
return a + b;
}
}).get();
System.out.println(res);
}
// grep the last digit from the string and check if it's odd/even
public static boolean isOdd(String x) {
if (x.length() > 1) {
if (x.substring(x.length()-1).equals("-")) {
x = x.substring(x.length()-3, x.length()-2);
}
else {
x = x.substring(x.length() - 1);
}
}
return Integer.parseInt(x) % 2 == 1;
}
OUTPUT
9-9-3-3444
How to Insert Dash Between Numbers and Text Javascript
Regular expression is a good option for such cases:
const str = "SSS1111abc545454xxxxxxxx66661111111XXXXX";
const separator = '_'
const result = str.match(/[a-z]+|\d+/ig).join(separator);
console.log(result);
How to add asterisk and hyphen between two adjacent even and odd numbers within a string
A couple of things I'd address:
1) If you loop to numbers.Length - 1
, you can avoid checking if there's a value2.
2) You can do a single both-numbers-even-or-odd check if you use the result of the modulo operation as an index into an array of delimiters.
3) When doing a bunch of string concatenations, I always try to use a StringBulder
.
string numbers = "12467930";
char[] delimiters = { '-', '*' };
StringBuilder result = new StringBuilder(numbers.Length * 2);
for (int i = 0; i < numbers.Length - 1; ++i)
{
int value1 = (int)char.GetNumericValue(numbers[i]);
int value2 = (int)char.GetNumericValue(numbers[i + 1]);
int mod1 = value1 % 2;
int mod2 = value2 % 2;
if (value1 != 0 && mod1 == mod2)
result.AppendFormat("{0}{1}", value1, delimiters[mod1]);
else
result.Append(value1);
}
result.Append(numbers.Last());
return result.ToString();
Entering dash between numbers in Javascript
Numbers don't have a length
property so numbers.length
will be undefined
.
You probably want to cast to string first, e.g.:
numbers = String(numbers);
Related Topics
Converting String Date in React/Javascript
Fetch() Unexpected End of Input
How to Partition Input Field to Appear as Separate Input Fields on Screen
Concatenate Json to a String in JavaScript
How to Apply CSS to Parent Using Child Selector - With CSS or Angular 2
Display Current Date in Dd/Mm/Yyyy Format
Input Field Value Should Not Be Greater Than Other Field Value
Move Items in Ul Li Up and Down
Open Link in a Window Using Script (Google Sheet)
Development Server of Create-React-App Does Not Auto Refresh
React: Do Children Always Rerender When the Parent Component Rerenders
Remove Insignificant Trailing Zeros from a Number
How to Convert Gmt Time to Ist Time in JavaScript
Disable Chrome Strict Mime Type Checking
Select Value of Input Element Inside HTML Table Using Jquery
Safari Browser Audio.Play() Is Not Working