I have string like below which i'd like to split by comma's. But there's an issue with the money which is also has comma in it.
What i like to achieve; if there's a number after comma do not seperate from that one. I'd like to do the job with javascript.
025056-03110,245056030,1,Standart Discount,Standart Discount,15,940.00USD,29/11/2017,1,
What i've tried so far with thousand combinations;
[^\,!\?]+
What i expect as a result;
025056-03110
245056030
1
Standart Discount
Standart Discount
*15,940.00USD*
29/11/2017
1
The solution here is to use .match() with this regex /(\d+,\d{3}[.]\d+\w+)|(\d+[\-][\d\w]+)|([\/\d\s\w]+)/g, it will split all the elements and skip the numbers that have a comma.
This is how should be your code:
var str = "025056-03110,245056030,1,Standart Discount,Standart Discount,15,940.00USD,29/11/2017,1";
var matches = str.match(/(\d+,\d{3}[.]\d+\w+)|(\d+[\-][\d\w]+)|([\/\d\s\w]+)/g);
Demo:
var str = "025056-03110,245056030,1,Standart Discount,Standart Discount,15,940.00USD,29/11/2017,1";
var matches = str.match(/(\d+,\d{3}[.]\d+\w+)|(\d+[\-][\d\w]+)|([\/\d\s\w]+)/g);
console.log(matches);
let str = '025056-03110,245056030,1,Standart Discount,Standart Discount,15,940.00USD,29/11/2017,1,';
let price = str.match(/[A-Za-z],(\d+,?\d{1,3}\.\d{2}\w{3})/)[1];
let temp = price.replace(',', '|');
console.log(
str.replace(price, temp)
.split(',')
.map(v => v.replace('|', ','))
.filter(v => v)
);
Maybe you could do it like this:
(?:\d+,(?=\d+\.).+?(?=,)|[\w-\/.\s]+)
var pattern = /(?:\d+,(?=\d+\.).+?(?=,)|[\w-\/.\s]+)/g;
var str = "025056-03110,245056030,1,Standart Discount,Standart Discount,15,940.00USD,29/11/2017,1,";
var matches = str.match(pattern);
for (var i = 0; i < matches.length; i++) {
if (matches[i].indexOf('USD') !== -1) {
matches[i] = "*" + matches[i] + "*";
}
}
console.log(matches.join('\n'));
Rather match with alternatives: \*[^*]*\*|[^\s,][^,]*
var s = '025056-03110,245056030,1,Standart Discount,Standart Discount,*15,940.00USD*,29/11/2017,1,';
var res = s.match(/\*[^*]*\*|[^\s,][^,]*/g);
console.log(res);
Related
I am very new to coding. I am having issue solving this following:
taking a data block ex:
1963;john, doe;Williwanka,tp;jane;4200;1300;19.63;-42
and covert into something like
1963,"john, doe","Williwanka,tp",jane,4200,1300,19.63,-42
I know I can use split() and join() however having trouble sorting through the string separated by comma "," and add double quote.
let text = "00077;Jessica;Williamsburg,ky;40769;42;42;42;42";
var myArray = text.split(";");
var newText = "";
for (var i = 0; i <= myArray.length; i++) {
if (myArray.indexOf(i) == ",") {
let newText = '"' + fruits.join('","') + '"';
} else {
newText += text.index(i);
}
}
return newText
Split by semicolons, then for each part, check if it includes a comma. If it does, wrap it in quotes, otherwise, don't change it. Then join the result into a string.
const text = "1963;john, doe;Williwanka,tp;jane;4200;1300;19.63;-42";
const parts = text.split(";");
const result = parts.map((p) => p.includes(",") ? `"${p}"` : p).join(",");
console.log(result);
You could use the regex /([^;]+)(?:;|$)/ and replace the first capturing group with " if it cannot be parsed to a number.
const input = "1963;john, doe;Williwanka,tp;jane;4200;1300;19.63;-42",
replacer = (_, p1) => isNaN(p1) ? `"${p1}",` : `${p1},`,
output = input.replace(/([^;]+)(?:;|$)/g, replacer).slice(0, -1);
console.log(output)
While the previous answers are correctly fine, it might be hard to understand how they work for a novice programmer.
Allow me to fix give you another answer below which is based on a simple loop like the OPs original code.
let text = "00077;Jessica;Williamsburg,ky;40769;42;42;42;42";
var partsArray = text.split(";");
var newText = "";
for (var i = 0; i < partsArray.length; i++) {
let onePart = partsArray[i];
if (onePart.includes(",")) {
newText += `"${onePart}"`;
} else {
newText += onePart;
}
newText += ",";
}
console.log(newText);
hello I have values like this
1-10
2-3
901-321
I want to get the reverse values for example like this
10-1
3-2
321-901
I have tried this
var str = "1-18";
var newString = "";
for (var i = str.length - 1; i >= 0; i--) {
newString += str[i];
}
return newString;
But it gives me 81-1
Instead, use String.split(), Arrary.reverse() and Arrary.join():
var str = '901-321';
var strArray = str.split('-'); // ['901', '321']
var strArrayReversed = strArray.reverse(); // ['321', '901']
var result = strArrayReversed.join('-'); // '321-901'
console.log('result = ', result);
// You can do all these steps above in one go as:
var result2 = str.split('-')
.reverse()
.join('-');
console.log('result2 = ', result2);
MDN Docs:
String.prototype.split()
Array.prototype.reverse()
Array.prototype.join()
Can split on the - to create array , reverse the array and join it back into string
var str = "1-18",
newStr = str.split('-').reverse().join('-');
console.log(newStr)
a = "12-5"
console.log(a.split('-').reverse().join('-'))
You can use the split method to divide the string in two, and then use the second part before the first, like this:
var str = "1-18";
var l = str.split("-");
return l[1] + "-" + l[0];
You could replace the string by swapping the values.
var string = '901-321';
console.log(string.replace(/(.+)-(.+)/, '$2-$1'));
function titleCase(str) {
var str1 = str.match(/\S+\s*/g);
var str2;
for(var i = 0; i < str1.length; i++){
str2 = str1[i].toLowerCase().replace(str1[i].charAt(0), str1[i].charAt(0).toUpperCase());
}
return str2.join(' ');
}
titleCase("I'm a little tea pot");
What's wrong with my code? str2.join is not a function
Easiest way to go about this is to split the string on every space, then set the first letter of each element in the array to the capitalized version of the letter and join it back.
What you are doing is assigning the value of the result to str2, having a string type rather than an array, that is why join is not working for you.
function titleCase(str) {
const words = str.split(' ');
for (let i = 0; i < words.length; i++) {
words[i] = words[i][0].toUpperCase() + words[i].slice(1);
}
return words.join(' ');
}
A slightly different variant with some ES6 favor to it:
const titleCase = str => {
const result = [];
for (const word of str.split(' ')) {
result.push(word[0].toUpperCase() + word.slice(1));
}
return result.join(' ');
};
If you want to ensure space characters such as tabs, newlines etc. work, you can split using your regex or replace all whitespace characters with spaces as a first step, e.g.:
const words = str.replace(/\s/g, ' ').split(' ').filter(word => word !== '');
function titleCase(str) {
var str1 = str.match(/\S+\s*/g);
var str2 = [];
for(var i = 0; i < str1.length; i++){
str2[i] = str1[i].replace(str1[i].charAt(0), str1[i].charAt(0).toUpperCase());
}
return str2.join(' ');
}
titleCase("I'm a little tea pot");
This is a simple solution to your problem. However, there are many ways to get the same result this is one of them.
function capitalize(str) {
let str2 = str[0].toUpperCase();
return str.replace(str[0], str2);
}
This function works fine.
But if i add more spaces in str than it gives the wrong count of words. Any help would be appreciated.
str = "coune me in"
var obj = {};
var regex = /[\s]/gi
function count(str){
// total spaces in a string
var spacesCount = str.match(regex).length;
// words count
var wordsCount = str.split(' ').length;
//charetcers count
var charsCount = str.split('').join('').length;
//average count
var avgCount = str.split(' ').join('').length/wordsCount;
// adding it to the object
obj.words = wordsCount;
obj.chars = charsCount;
obj.avgLength = avgCount;
obj.spaces = spacesCount;
return obj
}
count(str)
Try something like:
mystring.split(/\s+/);
This will split on one or more white-space characters so two spaces (or more) in a row will be treated as just one split.
let Allah = 'Allah is our creator.'
Allah = Allah.trim();
count = 0;
for (let i = 0; i < Allah.length; i++) {
let char = Allah[i];
if (char == " " && Allah[i-1] != " ") {//add here
count++;
}
}
count++;
console.log(count);
//output:4
I would like to replace every other comma in a string with a semicolon.
For example:
1,2,3,4,5,6,7,8,9,10
would become
1;2,3;4,5;6,7;8,9;10
What would be the regexp to do this? An explanation would be great.
Thank you :)
var myNums = "1,2,3,4,5,6,7,8,9,10";
myNums.replace(/(.*?),(.*?,)?/g,"$1;$2");
That'll do it.
var str = '1,2,3,4,5,6,7,8,9,10';
str.replace(/,(.*?,)?/g, ';$1');
// Now str === "1;2,3;4,5;6,7;8,9;10"
You would do something like this:
myString.replace(/,/g, ';');
You could use this regex pattern
([^,]*),([^,]*),?
And replace with $1;$2,. The question mark on the end is to account for the lack of a comma signaling the end of the last pair.
For example...
var theString = "1,2,3,4,5,6,7,8,9,10";
theString = theString.replace(/([^,]*),([^,]*),?/ig, "$1;$2,"); //returns "1;2,3;4,5;6,7;8,9;10,"
theString = theString.substring(0, theString.length - 1); //returns "1;2,3;4,5;6,7;8,9;10"
A non-regex answer:
function alternateDelims(array, delim_one, delim_two) {
var delim = delim_one,
len = array.length,
result = [];
for(var i = 0; i < len; i += 1) {
result.push(array[i]);
if(i < len-1) { result.push(delim); }
delim = (delim === delim_one) ? delim_two : delim_one;
}
return result.join('');
}
nums = "1,2,3,4,5,6,7,8,9,10"
alternateDelims(nums.split(','), ';', ',');