JavaScript: Add space between Char and Number with Regex - javascript

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);

Related

how to split string every 2 character

var alphabet = "FIN SLHOJVHEN GYKOHU";
I want to split it every 2 character so it would print
"I LOVE YOU "
I already try this but it didn't work
for (var i = 0 ; i \< alphabet.length ; i+=2 ){
alphabet.split(i)
correct me please
You can transform the string into an array, filter it and make it a string again.
let alphabet = "FIN SLHOJVHEN GYKOHU";
alphabet = [...alphabet].filter((_, i) => i%2).join("");
console.log(alphabet); //I LOVE YOU;
Also this one results in I LOVE YOU (regex101 demo).
// the string
let alphabet = 'FIN SLHOJVHEN GYKOHU';
// capture ^ start or chr, match latter chr
alphabet = alphabet.replace(/(^|.)./g, '$1');
console.log(alphabet);
Since the split function will split the given string by the delimiter you passed, it seems to me that you wish to first split the words (using empty space) contained in the encoded string and only then take only the characters at even positions to include in the decoded string.
This is a demo achieving that:
const encoded = "FIN SLHOJVHEN GYKOHU";
const words = encoded.split(' ');
let decoded = '';
words.forEach((word)=>{
for (let i=1;i<word.length;i+=2){
decoded += word[i];
}
decoded += ' ';
});
console.log(decoded);
Using a regex replacement approach we can try:
var alphabet = "FIN SLHOJVHEN GYKOHU";
var output = alphabet.replace(/[A-Z]([A-Z]|(?=\s))/g, "$1");
console.log(output);
Here is an explanation of the regex pattern:
[A-Z] match a single (odd) uppercase letter
( open capture
[A-Z] an uppercase letter
| OR
(?=\s) lookahead and find a space
)
In other words, we match an odd letter and then capture the next letter, unless that odd letter happen to be the last in the word. Then we replace with just the captured even letter, if available.
you already have different ways to do it, I'm adding one, so you'll get totally confused! hehe
This one is recursive:
we take your string alphabet
first 2 letters (every 2)
last one of this 2 characters string is stored in toPrint variable
delete the first 2 characters from alphabet
... loop till alphabet empty
Your toPrint has I Love You
Certainly not the fastest one, but nice.
let alphabet = "FIN SLHOJVHEN GYKOHU";
let toPrint = '';
do {
let temp = alphabet.slice(0, 2);
toPrint += temp[1];
alphabet = alphabet.slice(2, alphabet.length);
} while (alphabet !== '');
console.log(toPrint);
You can start your loop at 1 as you want every second character, and note that \< should be <
In the loop, i is the position of the character, so you would still have to get the character for that position and then assemble the resulting string.
var alphabet = "FIN SLHOJVHEN GYKOHU";
var result = "";
for (var i = 1; i < alphabet.length; i += 2) {
result += alphabet[i];
}
console.log(result);
If you want to take the spaces into account and only get the 2nd non whitespace character you might:
get the separate words by splitting on whitespace chars
remove the empty entries
join every second character to a string
join the parts from the initial split with a space
const alphabet = " FIN SLHOJVHEN GYKOHU ";
const result = alphabet
.split(/\s+/)
.filter(Boolean)
.map(s => s.split("").filter((s, i) => i % 2).join(""))
.join(" ");
console.log(result);
If you have a browser where a positive lookbehind for a regex is supported:
const alphabet = " FIN SLHOJVHEN GYKOHU ";
const result = alphabet
.split(/\s+/)
.filter(Boolean)
.map(s => s.match(/(?<=^(?:..)*.)./g).join(""))
.join(" ");
console.log(result);
var alphabet = "FIN SLHOJVHEN GYKOHU";
const arrayAlpha = alphabet.split('');
let stringToPrint = '';
for(let i=1; i<arrayAlpha.length; i+=2){
stringToPrint = stringToPrint + arrayAlpha[i]
}
console.log(stringToPrint)

Using regex with javascript to money string transform

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!

Javascript - Regex to replace last 4 digit

I have a number variable at JavaScript and i want it replaced in last 4 character. Example:
I have a number 123456789 and i want it to be replaced like this 12345****
Is there any regex to do that in JavaScript?
Use replace() with regex /\d{4}$/
var res = '123456789'.replace(/\d{4}$/, '****');
document.write(res);
Regex explanation
Or using substring() or substr()
var str = '123456789',
res = str.substr(0, str.length - 4) + '****';
document.write(res);
You could use substring as well:
var s = '123456789';
var ns = s.substring(0, s.length - 4) + '****';
document.write(ns);

JS Regex - Match each not escaped specific characters

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

javascript - count spaces before first character of a string

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.

Categories