Regular expression to count characters after coma - javascript

How can I build a regular expression that will replace each comma with a '.' decimal point if there are more than 3 or less than 3 digits.
that is 4,444 is correct and stay like that but 3,33 will be 3.33 or 4,4444 will be 4.444
similarly it can be like this as well 1,234,45,6789, and it should become 1,234.45.6789

function commaToDot(number) {
let regex = /^\d{1,3}(?:\,\d{3})*((?:,\d+)+)*?$/;
let matches = number.match(regex);
if (matches[1]) {
number = number.replace(matches[1], matches[1].replace(/,/g, '.'))
}
return number;
}
console.log(commaToDot('4,4444'));
console.log(commaToDot('5,555'));
console.log(commaToDot('3,33'));
console.log(commaToDot('1,234,45,6789'));
console.log(commaToDot('1,234,45,678,9'));
console.log(commaToDot('5,5,5,5,5'));
This will match everything after the numbers stop being part of the \d{1,3},\d{3} pattern, and replace their commas with dots.
From what I gather, this is what you are looking for.
Edit
After leaving my comment above to check validity of "1,333.22,333", I've had to re-write the regex slightly:
function commaToDot(number) {
let regex = /(?!,\d{3},)(,\d{0,2})|(,\d{4,})/g,
matches = number.match(regex);
if (matches) {
matches.forEach((match) => {
number = number.replace(match, match.replace(/,/g, '.'));
});
}
return number
}
console.log(commaToDot('1,234,45,678,9'));
console.log(commaToDot('4,4444'));
console.log(commaToDot('5,555'));
console.log(commaToDot('3,33'));
console.log(commaToDot('1,234,45,6789'));
console.log(commaToDot('5,5,5,5,5'));
console.log(commaToDot('12,345,678,90'));
This should now do what you would like it to do.

With RegExp.test() function and specific regex patterns:
var commaToDot = function(str){
if (/^-?\d+[,\d]+\d+$/.test(str) && /\d+,(\d{1,2}|\d{4,})\b/.test(str)){
var parts = str.split(',');
return parts.length > 2? parts[0] +','+ parts.slice(1).join('.') : parts.join('.');
} else {
return str;
}
};
console.log(commaToDot('4,4444'));
console.log(commaToDot('5,555'));
console.log(commaToDot('3,33'));
console.log(commaToDot('1,234,45,6789'));

Related

Escaping apostrophes and the like in JavaScript [duplicate]

I want to remove all special characters except space from a string using JavaScript.
For example,
abc's test#s
should output as
abcs tests.
You should use the string replace function, with a single regex.
Assuming by special characters, you mean anything that's not letter, here is a solution:
const str = "abc's test#s";
console.log(str.replace(/[^a-zA-Z ]/g, ""));
You can do it specifying the characters you want to remove:
string = string.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, '');
Alternatively, to change all characters except numbers and letters, try:
string = string.replace(/[^a-zA-Z0-9]/g, '');
The first solution does not work for any UTF-8 alphabet. (It will cut text such as Привіт). I have managed to create a function which does not use RegExp and use good UTF-8 support in the JavaScript engine. The idea is simple if a symbol is equal in uppercase and lowercase it is a special character. The only exception is made for whitespace.
function removeSpecials(str) {
var lower = str.toLowerCase();
var upper = str.toUpperCase();
var res = "";
for(var i=0; i<lower.length; ++i) {
if(lower[i] != upper[i] || lower[i].trim() === '')
res += str[i];
}
return res;
}
Update: Please note, that this solution works only for languages where there are small and capital letters. In languages like Chinese, this won't work.
Update 2: I came to the original solution when I was working on a fuzzy search. If you also trying to remove special characters to implement search functionality, there is a better approach. Use any transliteration library which will produce you string only from Latin characters and then the simple Regexp will do all magic of removing special characters. (This will work for Chinese also and you also will receive side benefits by making Tromsø == Tromso).
search all not (word characters || space):
str.replace(/[^\w ]/, '')
I don't know JavaScript, but isn't it possible using regex?
Something like [^\w\d\s] will match anything but digits, characters and whitespaces. It would be just a question to find the syntax in JavaScript.
I tried Seagul's very creative solution, but found it treated numbers also as special characters, which did not suit my needs. So here is my (failsafe) tweak of Seagul's solution...
//return true if char is a number
function isNumber (text) {
if(text) {
var reg = new RegExp('[0-9]+$');
return reg.test(text);
}
return false;
}
function removeSpecial (text) {
if(text) {
var lower = text.toLowerCase();
var upper = text.toUpperCase();
var result = "";
for(var i=0; i<lower.length; ++i) {
if(isNumber(text[i]) || (lower[i] != upper[i]) || (lower[i].trim() === '')) {
result += text[i];
}
}
return result;
}
return '';
}
const str = "abc's#thy#^g&test#s";
console.log(str.replace(/[^a-zA-Z ]/g, ""));
Try to use this one
var result= stringToReplace.replace(/[^\w\s]/g, '')
[^] is for negation, \w for [a-zA-Z0-9_] word characters and \s for space,
/[]/g for global
With regular expression
let string = "!#This tool removes $special *characters* /other/ than! digits, characters and spaces!!!$";
var NewString= string.replace(/[^\w\s]/gi, '');
console.log(NewString);
Result //This tool removes special characters other than digits characters and spaces
Live Example : https://helpseotools.com/text-tools/remove-special-characters
dot (.) may not be considered special. I have added an OR condition to Mozfet's & Seagull's answer:
function isNumber (text) {
reg = new RegExp('[0-9]+$');
if(text) {
return reg.test(text);
}
return false;
}
function removeSpecial (text) {
if(text) {
var lower = text.toLowerCase();
var upper = text.toUpperCase();
var result = "";
for(var i=0; i<lower.length; ++i) {
if(isNumber(text[i]) || (lower[i] != upper[i]) || (lower[i].trim() === '') || (lower[i].trim() === '.')) {
result += text[i];
}
}
return result;
}
return '';
}
Try this:
const strippedString = htmlString.replace(/(<([^>]+)>)/gi, "");
console.log(strippedString);
const input = `#if_1 $(PR_CONTRACT_END_DATE) == '23-09-2019' #
Test27919<alerts#imimobile.com> #elseif_1 $(PR_CONTRACT_START_DATE) == '20-09-2019' #
Sender539<rama.sns#gmail.com> #elseif_1 $(PR_ACCOUNT_ID) == '1234' #
AdestraSID<hello#imimobile.co> #else_1#Test27919<alerts#imimobile.com>#endif_1#`;
const replaceString = input.split('$(').join('->').split(')').join('<-');
console.log(replaceString.match(/(?<=->).*?(?=<-)/g));
Whose special characters you want to remove from a string, prepare a list of them and then user javascript replace function to remove all special characters.
var str = 'abc'de#;:sfjkewr47239847duifyh';
alert(str.replace("'","").replace("#","").replace(";","").replace(":",""));
or you can run loop for a whole string and compare single single character with the ASCII code and regenerate a new string.

Delete special characters from an ng-repeat list (parsed from CSV) [duplicate]

I want to remove all special characters except space from a string using JavaScript.
For example,
abc's test#s
should output as
abcs tests.
You should use the string replace function, with a single regex.
Assuming by special characters, you mean anything that's not letter, here is a solution:
const str = "abc's test#s";
console.log(str.replace(/[^a-zA-Z ]/g, ""));
You can do it specifying the characters you want to remove:
string = string.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, '');
Alternatively, to change all characters except numbers and letters, try:
string = string.replace(/[^a-zA-Z0-9]/g, '');
The first solution does not work for any UTF-8 alphabet. (It will cut text such as Привіт). I have managed to create a function which does not use RegExp and use good UTF-8 support in the JavaScript engine. The idea is simple if a symbol is equal in uppercase and lowercase it is a special character. The only exception is made for whitespace.
function removeSpecials(str) {
var lower = str.toLowerCase();
var upper = str.toUpperCase();
var res = "";
for(var i=0; i<lower.length; ++i) {
if(lower[i] != upper[i] || lower[i].trim() === '')
res += str[i];
}
return res;
}
Update: Please note, that this solution works only for languages where there are small and capital letters. In languages like Chinese, this won't work.
Update 2: I came to the original solution when I was working on a fuzzy search. If you also trying to remove special characters to implement search functionality, there is a better approach. Use any transliteration library which will produce you string only from Latin characters and then the simple Regexp will do all magic of removing special characters. (This will work for Chinese also and you also will receive side benefits by making Tromsø == Tromso).
search all not (word characters || space):
str.replace(/[^\w ]/, '')
I don't know JavaScript, but isn't it possible using regex?
Something like [^\w\d\s] will match anything but digits, characters and whitespaces. It would be just a question to find the syntax in JavaScript.
I tried Seagul's very creative solution, but found it treated numbers also as special characters, which did not suit my needs. So here is my (failsafe) tweak of Seagul's solution...
//return true if char is a number
function isNumber (text) {
if(text) {
var reg = new RegExp('[0-9]+$');
return reg.test(text);
}
return false;
}
function removeSpecial (text) {
if(text) {
var lower = text.toLowerCase();
var upper = text.toUpperCase();
var result = "";
for(var i=0; i<lower.length; ++i) {
if(isNumber(text[i]) || (lower[i] != upper[i]) || (lower[i].trim() === '')) {
result += text[i];
}
}
return result;
}
return '';
}
const str = "abc's#thy#^g&test#s";
console.log(str.replace(/[^a-zA-Z ]/g, ""));
Try to use this one
var result= stringToReplace.replace(/[^\w\s]/g, '')
[^] is for negation, \w for [a-zA-Z0-9_] word characters and \s for space,
/[]/g for global
With regular expression
let string = "!#This tool removes $special *characters* /other/ than! digits, characters and spaces!!!$";
var NewString= string.replace(/[^\w\s]/gi, '');
console.log(NewString);
Result //This tool removes special characters other than digits characters and spaces
Live Example : https://helpseotools.com/text-tools/remove-special-characters
dot (.) may not be considered special. I have added an OR condition to Mozfet's & Seagull's answer:
function isNumber (text) {
reg = new RegExp('[0-9]+$');
if(text) {
return reg.test(text);
}
return false;
}
function removeSpecial (text) {
if(text) {
var lower = text.toLowerCase();
var upper = text.toUpperCase();
var result = "";
for(var i=0; i<lower.length; ++i) {
if(isNumber(text[i]) || (lower[i] != upper[i]) || (lower[i].trim() === '') || (lower[i].trim() === '.')) {
result += text[i];
}
}
return result;
}
return '';
}
Try this:
const strippedString = htmlString.replace(/(<([^>]+)>)/gi, "");
console.log(strippedString);
const input = `#if_1 $(PR_CONTRACT_END_DATE) == '23-09-2019' #
Test27919<alerts#imimobile.com> #elseif_1 $(PR_CONTRACT_START_DATE) == '20-09-2019' #
Sender539<rama.sns#gmail.com> #elseif_1 $(PR_ACCOUNT_ID) == '1234' #
AdestraSID<hello#imimobile.co> #else_1#Test27919<alerts#imimobile.com>#endif_1#`;
const replaceString = input.split('$(').join('->').split(')').join('<-');
console.log(replaceString.match(/(?<=->).*?(?=<-)/g));
Whose special characters you want to remove from a string, prepare a list of them and then user javascript replace function to remove all special characters.
var str = 'abc'de#;:sfjkewr47239847duifyh';
alert(str.replace("'","").replace("#","").replace(";","").replace(":",""));
or you can run loop for a whole string and compare single single character with the ASCII code and regenerate a new string.

Find letters in random string exactly, using RegEx

The emphasis here is on the word exactly. This needs to work for any number of permutations, so hopefully my example is clear enough.
Given a string of random letters, is it possible (using RegEx) to match an exact number of letters within the given string?
So if I have a string (str1) containing letters ABZBABJDCDAZ and I wanted to match the letters JDBBAA (str2), my function should return true because str1 contains all the right letters enough times. If however str1 were to be changed to ABAJDCDA, then the function would return false as str2 requires that str1 have at least 2 instances of the letter B.
This is what I have so far using a range:
const findLetters = (str1, str2) => {
const regex = new RegExp(`[${str2}]`, 'g')
const result = (str1.match(regex))
console.log(result)
}
findLetters('ABZBABJDCDAZ', 'JDBBAA')
As you can see it matches the right letters, but it matches all instances of them. Is there any way to do what I'm trying to do using RegEx? The reason I'm focusing on RegEx here is because I need this code to be highly optimised, and so far my other functions using Array.every() and indexOf() are just too slow.
Note: My function only requires to return a true/false value.
Try (here we sort letters of both strings and then create regexp like A.*A.*B.*B.*D.*J)
const findLetters = (str1, str2) => {
const regex = new RegExp([...str2].sort().join`.*`)
return regex.test([...str1].sort().join``)
}
console.log( findLetters('ABZBABJDCDAZ', 'JDBBAA') );
console.log( findLetters('ABAJDCDA', 'JDBBAA') );
I dont know if regex is the right way for this as this can also get very expensive. Regex is fast, but not always the fastest.
const findLetters2 = (strSearchIn, strSearchFor) => {
var strSearchInSorted = strSearchIn.split('').sort(function(a, b) {
return a.localeCompare(b);
});
var strSearchForSorted = strSearchFor.split('').sort(function(a, b) {
return a.localeCompare(b);
});
return hasAllChars(strSearchInSorted, strSearchForSorted);
}
const hasAllChars = (searchInCharList, searchCharList) => {
var counter = 0;
for (i = 0; i < searchCharList.length; i++) {
var found = false;
for (counter; counter < searchInCharList.length;) {
counter++;
if (searchCharList[i] == searchInCharList[counter - 1]) {
found = true;
break;
}
}
if (found == false) return false;
}
return true;
}
// No-Regex solution
console.log('true: ' + findLetters2('abcABC', 'abcABC'));
console.log('true: ' + findLetters2('abcABC', 'acbACB'));
console.log('true: ' + findLetters2('abcABCx', 'acbACB'));
console.log('false: ' + findLetters2('abcABC', 'acbACBx'));
console.log('true: ' + findLetters2('ahfffmbbbertwcAtzrBCasdf', 'acbACB'));
console.log('false: ' + findLetters2('abcABC', 'acbAACB'));
Feel free to test it's speed and to optimize it as I'm no js expert. This solution should iterate each string once after sorting. Sorting is thanks to https://stackoverflow.com/a/51169/9338645.

How to split a string at commas but ignore \,?

I want to split string http://some.com/\,brabra,400,500 into ['http://some.com/\,brabra', 400, 500]
I already tried this, but error because lookbehind is not support in js.
'http://some.com/\,brabra,400,500'.split(/(?<!\\),/g)
Any other ideas to do this?
You may use matching approach with (?:[^,\\]+|\\.)+:
match(/(?:[^,\\]+|\\.)+/g)
See the regex demo
Details: the (?:[^,\\]+|\\.)+ matches 1 or more occurrences ((?:...)+) of a 1+ characters other than , and \ (with [^,\\]+) or (|) any escaped sequence (\\.)
var s = "http://some.com/\\,brabra,400,500"
console.log(s.match(/(?:[^,\\]+|\\.)+/g));
Or a workaround if the comma to be split with is always followed with a digit:
split(/,(?=\d)/)
See this regex demo
var s = "http://some.com/\\,brabra,400,500"
console.log(s.split(/,(?=\d)/));
A classic, if slightly inelegant approach for such problems is to replace some characters with a magic token, then put them back later:
str
.replace("\\,", "DONT_SPLIT_HERE")
.split(',')
.map(part => part.replace("DONT_SPLIT_HERE", "\\,")
you can use simulate positive lookaheads with reversing the string:
String.prototype.reverse = function() {
return this.split("").reverse().join("");
}
Array.prototype.reverseElements = function() {
var ar = [];
for (var i = 0; i < this.length; i++) {
if (typeof this[i] === 'string')
ar[i] = this[i].reverse();
else {
//Do something if not a String
}
}
return ar;
}
var str = "http://some.com/\,brabra,400,500";
var ar = str.reverse().split(/,(?!\\)/).reverse().reverseElements();
console.log(ar);
Note: The Regex works here, but not in the snippet.

Convert dash-separated string to camelCase?

For example suppose I always have a string that is delimited by "-". Is there a way to transform
it-is-a-great-day-today
to
itIsAGreatDayToday
Using RegEx?
Yes (edited to support non-lowercase input and Unicode):
function camelCase(input) {
return input.toLowerCase().replace(/-(.)/g, function(match, group1) {
return group1.toUpperCase();
});
}
See more about "replace callbacks" on MDN's "Specifying a function as a parameter" documentation.
The first argument to the callback function is the full match, and subsequent arguments are the parenthesized groups in the regex (in this case, the character after the the hyphen).
Another method using reduce:
function camelCase(str) {
return str
.split('-')
.reduce((a, b) => a + b.charAt(0).toUpperCase() + b.slice(1));
}
You can match on the word character after each dash (-) or the start of the string, or you could simplify by matching the word character after each word boundary (\b):
function camelCase(s) {
return (s||'').toLowerCase().replace(/(\b|-)\w/g, function(m) {
return m.toUpperCase().replace(/-/,'');
});
}
camelCase('foo-bar'); // => 'FooBar'
camelCase('FOo-BaR-gAH'); // => 'FooBarGah'
Here's a demo
var test = 'It-is-a-great-day-today';
function camelize(str) {
return str[0].toLowerCase() + str.replace(/-([a-z])/g, function(a, b) {
return b.toUpperCase();
}).slice(1);
}
console.log(camelize(test));
This should also work:
function camelCase(str) {
return str.replace(/^.|-./g, function(letter, index) {
return index == 0 ? letter.toLowerCase() : letter.substr(1).toUpperCase();
});
}
And IMHO it is little bit more efficient since we're not converting whole input string to lowercase first and then convert to uppercase if needed. This function only converts first letter to lowercase and then every character after hyphen - to uppercase.
See http://jsfiddle.net/54ZcM/
function camelCase(string) {
return string.toLowerCase().replace(/(\-[a-zA-Z])/g, function($1) {
return $1.toUpperCase().replace('-','');
})
}
alert(camelCase('fOo-BarBA-fo'));
I know this question is a bit old but,
Here's my version of camelCase function:
var camelCase = (function () {
var DEFAULT_REGEX = /[-_]+(.)?/g;
function toUpper(match, group1) {
return group1 ? group1.toUpperCase() : '';
}
return function (str, delimiters) {
return str.replace(delimiters ? new RegExp('[' + delimiters + ']+(.)?', 'g') : DEFAULT_REGEX, toUpper);
};
})();
It handles all of the following edge cases:
takes care of both underscores and hyphens by default (configurable with second parameter)
string with unicode characters
string that ends with hyphens or underscore
string that has consecutive hyphens or underscores
Here's a link to live tests: http://jsfiddle.net/avKzf/2/
Here are results from tests:
input: "ab-cd-ef", result: "abCdEf"
input: "ab-cd-ef-", result: "abCdEf"
input: "ab-cd-ef--", result: "abCdEf"
input: "ab-cd--ef--", result: "abCdEf"
input: "--ab-cd--ef--", result: "AbCdEf"
input: "--ab-cd-__-ef--", result: "AbCdEf"
Notice that strings that start with delimiters will result in a uppercase letter at the beginning.
If that is not what you would expect, you can always use lcfirst.
Here's my lcfirst if you need it:
function lcfirst(str) {
return str && str.charAt(0).toLowerCase() + str.substring(1);
}
This works great but someone might be able to clean it up.
var toCamelCase = function(str) {
// Replace special characters with a space
str = str.replace(/[^a-zA-Z0-9 ]/g, " ");
// put a space before an uppercase letter
str = str.replace(/([a-z](?=[A-Z]))/g, '$1 ');
// Lower case first character and some other stuff that I don't understand
str = str.replace(/([^a-zA-Z0-9 ])|^[0-9]+/g, '').trim().toLowerCase();
// uppercase characters preceded by a space or number
str = str.replace(/([ 0-9]+)([a-zA-Z])/g, function(a,b,c) {
return b.trim() + c.toUpperCase();
});
return str;
};
console.log(toCamelCase('hyphen~name~ format'));
console.log(toCamelCase('hyphen.name.format'));
console.log(toCamelCase('hyphen-name-format'));
console.log(toCamelCase('Hyphen-Dame-Gormat'));
console.log(toCamelCase('EquipmentClass name'));
console.log(toCamelCase('Equipment className'));
console.log(toCamelCase('equipment class name'));
console.log(toCamelCase(' e Equipment Class Name'));
console.log(toCamelCase('under9score_name_format'));
console.log(toCamelCase('Enderscore_name_format'));
console.log(toCamelCase('EnderscoreBameFormat'));
console.log(toCamelCase('_EnderscoreBameFormat'));
http://jsbin.com/yageqi/1/edit?js,console
'it-is-a-great-day-today'.split('-').map(function(x,i){
return (i?x[0].toUpperCase():x[0]) + x.slice(1).toLowerCase()
}).join('')
Result:
'itIsAGreatDayToday'
Alternatively, .match(/\w+/g) rather than .split('-') -- depending on what you want to do in edge cases like "this--is-a-test".
var string = "it-is-a-great-day-today";
or
var string = "it_is_a_great_day_today";
var regex = /(_|-)([a-z])/g;
string.toLowerCase().replace(regex, toCamelCase );
function toCamelCase( string ){
return string[1].toUpperCase();
}
Output: "itIsAGreatDayToday";
here is the jsfiddle you can play with to test this
http://jsfiddle.net/5n84w/2/
```
/**
* Function to convert any string to camelCase
* var regex = 'chetan-Ankola###.com---m13ok#-#alo(*finding!R%S#%-GFF';
* Where [-_ .] is the seperator, you can add eg: '#' too
* + is to handle repetition of seperator
* ? is to take care of preceeding token
* match nov(ember)? matches nov and november
*/
var camelCaser = function (str) {
var camelCased = str.replace(/[-_ .]+(.)?/g, function (match, p) {
if (p) {
return p.toUpperCase();
}
return '';
}).replace(/[^\w]/gi, '');
return camelCased;
};
```
lodash.camelCase can be another option
Sample:
const str = 'it-is-a-great-day-today';
lodash.camelCase(str.split('-'));
result: itIsAGreatDayToday
Better do this guys,
function camelCase(data) {
var tmp;
if (data && typeof data === 'object') {
forEach(data, function (value, key) {
var tmpvalue = camelCase(key);
tmp[tmpvalue] = value;
});
return tmp;
} else {
return data.toLowerCase().replace(/(\_\w)/g, function (m) { return m[1].toUpperCase() }).replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
}
}
console.log(camelCase("SucCCCess_dfds_dsqsdqs-dsdqs-dqsdqs"));
Works perfectly in any cases.
$scope.toCamelCase = function(arg){
var arg = arg.toLowerCase();
var arr = arg.split("");
arr[0] = arr[0].toUpperCase();
return arr.join("");
};

Categories

Resources