I want to cut zeros from the beginning of the string in the calculation rules but don't want to make it a number.
I want something like this:
'000' // '0'
'050' // '50'
'076' // '76'
'135' // '135'
'107' // '107'
CodePudding user response:
You can use a regular expression that searches for leading zeros (but excludes the last zero if the string consists solely of zeros):
const trimLeadingZeros = s => s.replace(/^0 (?!$)/, '');
console.log(trimLeadingZeros('000'));
console.log(trimLeadingZeros('050'));
console.log(trimLeadingZeros('076'));
console.log(trimLeadingZeros('135'));
console.log(trimLeadingZeros('107'));
Converting to a number and back to a string fails for large numbers. For example, Number('9999999999999999').toString()
yields '10000000000000000'
.
CodePudding user response:
You can just convert it into a Number and then back to a String: Number('005').toString()
.
If you cant use Number
, go for a regex: '005'.replace(/^(0(?!$)) /, '')
Demos below:
const test = (s) => console.log(s, '-->', s.replace(/^(0(?!$)) /, ''));
test('000');
test('005');
test('076');
test('136');
test('107');
const test = (s) => console.log(s, '-->', Number(s).toString());
test('000');
test('005');
test('076');
test('136');
CodePudding user response:
If you absolutely can't convert to a Number
, then you can use .split()
and .reduce()
function removeLeadingZeros(str) {
const chrs = str.split('');
return chrs.filter((ch, i) => ch !== '0' || i === chrs.length-1).join('');
}
console.log(removeLeadingZeros('000')); // => 0
console.log(removeLeadingZeros('050')); // => 50
console.log(removeLeadingZeros('076')); // => 76
console.log(removeLeadingZeros('135')); // => 135
CodePudding user response:
Here's an example solution using iteration instead of a regular expression:
The input string is iterated by Unicode code points until the first substring fails to match the target value — or the iterator is exhausted. At that point, the input string is sliced on the current iteration index and returned.
Your example data requests special behavior for strings comprised of all zeroes, so that case is handled in the second function.
/**
* @param {string} inputStr The input string
* @param {string} char The character to trim
* @returns {string}
*/
function trimLeading (inputStr, char = ' ') {
let index = 0;
for (const s of inputStr) {
if (s !== char) break;
index = s.length;
}
return inputStr.slice(index);
}
/**
* Special case behavior for an input with only zeroes
*
* @param {string} inputStr The input string
* @returns {string}
*/
function trimLeadingZeroes (inputStr) {
const result = trimLeading(inputStr, '0');
return result.length > 0 ? result : '0';
}
const inputs = [
'000', // '0'
'050', // '50'
'076', // '76'
'135', // '135'
'107', // '107'
];
const results = inputs.map(trimLeadingZeroes);
console.log(results);
// Example with multi-byte unicode:
const blackCat = '