I have a string that I would like to break down into an array.
Each index needs to have a max letter, say 15 characters. Each point needs to be at a words end, with no overlap of the maximum characters (IE would stop at 28 chars before heading into next word).
I've been able to do similar things using regex in the past, but I'm trying to make this work with an online platform that does not like regex.
Example string:
Hi this is a sample string that I would like to break down into an array!
Desired result # 15 char max:
Hi this is a
sample string
that I would
like to break
down into an
array!
Considering there's no word bigger then max limit
function splitString (n,str){
let arr = str?.split(' ');
let result=[]
let subStr=arr[0]
for(let i = 1; i < arr.length; i++){
let word = arr[i]
if(subStr.length + word.length + 1 <= n){
subStr = subStr + ' ' + word
}
else{
result.push(subStr);
subStr = word
}
}
if(subStr.length){result.push(subStr)}
return result
}
console.log(splitString(15,'Hi this is a sample string that I would like to break down into an array!'))
I have a money value as "R$ 2.200,00" where my thousand separators are . and my decimal separator is ,.
I would like um regex to transform this string into a valid MySQL decimal number.
Possible values:
"R$ 23.000,20", "23.000,30", "R$ 1300,20", "R$ 100", "161,43256"
The results would be:
"23000.20", "23000.30", "1300.20", "100", "161.43256"
My attempt is below, but it does not work. I would like to accept only numbers and dot(.) for the results.
const str = "R$ 2.200,000";
const res = str
.replace(/R$/gi, "")
.replace(/./gi, "")
.replace(/,/gi, ".");
console.log(res);
With optimisations this seems to be working:
const possible = [
"R$ 23.000,20",
"23.000,30",
"R$ 1300,20",
"R$ 100 ",
"161,43256",
"R$ -23.000,20",
"-23.000,30",
"R$ -1300,20",
"R$ -100",
"-161,43256"
]
const rx = /[^-\d,]+/g // Match everything except digits, comma, dot and negative
const parseNumber = num =>
num
.replace(rx, '') // Filter out non numeric entities
.replace(',', '.') // Replacing comma with dot
possible.forEach(num => {
console.log(num, '\t->\t', parseNumber(num))
})
this regEx replace/remove: (/[^\w\s]/gi) all special globaly signs ("$", ".", ","),
next one give the digit part (/\D/g)
and finally with string methods substring(,) place a ',' between the last two digits in the length of the string.
let input = "R$ 2.200,000";
let res = input.replace(/[^\w\s]/gi, '')
let str = res.replace(/\D/g,'');
let resStr = str.substring(0,str.length-2)+"."+str.substring(str.length-2);
console.log(resStr)
Edit: However this will not work if you have more than one thousand seperator, do not use it if you may have.
So, if you don't have to use regex, you can use replace function with strings too.
const str = "R$ 2.200,00";
const res = str
.replace('R$ ', "")
.replace('.', "")
.replace(',', ".")
console.log(res);
The code above will give you the format you want as a String. If you need Float, you can use parseFloat function.
console.log(parseFloat(res));
You can even use toFixed if you want absolute number of numbers after floating point
console.log(parseFloat(res).toFixed(5));
let input1 = "R$ 2.200,000";
let input2 = "23.000,30";
let input3 = "R$ 1300,20";
let input4 = "R$ 100";
let input5 = "161,43256";
const formatMoney = (inpStr) => {
let res = inpStr
res = res.replace(/[$R\s]/g, '');
let idx = res.indexOf('.')
res = res.replace(/,/, '.')
for (let i in res) {
if (res[i] === '.' && i !== i) {
res[i] = ','
}
}
return res
}
console.log(formatMoney(input1))
console.log(formatMoney(input2))
console.log(formatMoney(input3))
console.log(formatMoney(input4))
console.log(formatMoney(input5))
You could do that in two steps.
Step 1: remove characters
Substitute matches of the following regular expression with empty strings.
/(?:^R\$ +|[,.](?=.*[,.]))/gm
This will convert the strings
R$ 23.000,20
23.000,30
R$ 1300,20
R$ 100
161,43256
R$ 23.123.000,20
to
23000,20
23000,30
1300,20
100
161,43256
23123000,20
Javascript's regex engine performs the following steps.
(?: : begin a non-capture groups
^ : beginning of string
R\$ + : match 'R$' followed by 1+ spaces
| : or
[,.] : match ',' or '.'
(?= : begin positive lookahead
.* : match 0+ characters other than line terminators
[,.] : match ',' or '.'
) : end positive lookahead
) : end non-capture group
Step 2: convert comma, if present, to a period
Substitute matches of the following regular expression with a period.
/[,.]/gm
That would convert the above strings to the following.
23000.20
23000.30
1300.20
100
161.43256
23123000.20
Restart your engine!
Hello I have a plate number BZ8345LK and want convert to BZ 8345 LK (adding space between char and number).
I tried with this Regex but not working, only space first char with number. Ex BZ 8345LK, the 'LK' keep not space with number.
var str = 'BZ8345LK';
str.replace(/[^0-9](?=[0-9])/g, '$& ');
# return BZ 8345LK, I want BZ 8345 LK
You can use this regex
[a-z](?=\d)|\d(?=[a-z])
[a-z](?=\d) - Match any alphabet followed by digit
| - Alternation same as logical OR
\d(?=[a-z]) - Any digit followed by alphabet
let str = 'BZ8345LK'
let op = str.replace(/[a-z](?=\d)|\d(?=[a-z])/gi, '$& ')
console.log(op)
You should alternate with the other possibility, that a number is followed by a non-number:
var str = 'BZ8345LK';
console.log(str.replace(/[^0-9](?=[0-9])|[0-9](?=[^0-9])/g, '$& '));
An anoher option is to use:
^[^\d]+|[\d]{4}
Search for any not numeric character [^\d] followed by 4 numeric [\d]{4} characters
const str = 'BZ8345LK'
let answer = str.replace(/^[^\d]+|[\d]{4}/gi, '$& ')
console.log(answer)
Try with this
var str = "BZ8345LK";
var result = str.replace(/([A-Z]+)(\d+)([A-Z]+)/, "$1 $2 $3");
console.log(result);
I'm trying to make a Regex in JavaScript to match each not escaped specific characters.
Here I'm looking for all the ' characters. They can be at the beginning or the end of the string, and consecutive.
E.g.:
'abc''abc\'abc
I should get 3 matchs: the 1st, 5 and 6th character. But not 11th which escaped.
You'll have to account for cases like \\' which should match, and \\\' which shouldn't. but you don't have lookbehinds in JS, let alone variable-length lookbehinds, so you'll have to use something else.
Use the following regex:
\\.|(')
This will match both all escaped characters and the ' characters you're looking for, but the quotes will be in a capture group.
Look at this demo. The matches you're interested in are in green, the ones to ignore are in blue.
Then, in JS, ignore each match object m where !m[1].
Example:
var input = "'abc''abc\\'abc \\\\' abc";
var re = /\\.|(')/g;
var m;
var positions = [];
while (m = re.exec(input)) {
if (m[1])
positions.push(m.index);
}
var pos = [];
for (var i = 0; i < input.length; ++i) {
pos.push(positions.indexOf(i) >= 0 ? "^" : " ");
}
document.getElementById("output").innerText = input + "\n" + pos.join("");
<pre id="output"></pre>
You can use:
var s = "'abc''abc\\'abc";
var cnt=0;
s.replace(/\\?'/g, function($0) { if ($0[0] != '\\') cnt++; return $0;});
console.log(cnt);
//=> 3
What is the best way to count how many spaces before the fist character of a string?
str0 = 'nospaces even with other spaces still bring back zero';
str1 = ' onespace do not care about other spaces';
str2 = ' twospaces';
Use String.prototype.search
' foo'.search(/\S/); // 4, index of first non whitespace char
EDIT:
You can search for "Non whitespace characters, OR end of input" to avoid checking for -1.
' '.search(/\S|$/)
Using the following regex:
/^\s*/
in String.prototype.match() will result in an array with a single item, the length of which will tell you how many whitespace chars there were at the start of the string.
pttrn = /^\s*/;
str0 = 'nospaces';
len0 = str0.match(pttrn)[0].length;
str1 = ' onespace do not care about other spaces';
len1 = str1.match(pttrn)[0].length;
str2 = ' twospaces';
len2 = str2.match(pttrn)[0].length;
Remember that this will also match tab chars, each of which will count as one.
You could use trimLeft() as follows
myString.length - myString.trimLeft().length
Proof it works:
let myString = ' hello there '
let spacesAtStart = myString.length - myString.trimLeft().length
console.log(spacesAtStart)
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/TrimLeft
str0 = 'nospaces';
str1 = ' onespace do not care about other spaces';
str2 = ' twospaces';
arr_str0 = str0.match(/^[\s]*/g);
count1 = arr_str0[0].length;
console.log(count1);
arr_str1 = str1.match(/^[\s]*/g);
count2 = arr_str1[0].length;
console.log(count2);
arr_str2 = str2.match(/^[\s]*/g);
count3 = arr_str2[0].length;
console.log(count3);
Here:
I have used regular expression to count the number of spaces before the fist character of a string.
^ : start of string.
\s : for space
[ : beginning of character group
] : end of character group
str.match(/^\s*/)[0].length
str is the string.