I am trying to make a function that adds a space between "flight" and "###" but would like to make it work if the flight number is greater than 3 digits. I know I could make the second part of the slice method a huge number and it would technically work but I figure there should be a more elegant way. Any help would be appreciated, thanks!
const addSpace = function (str) {
const flightNumber = str.slice(6, 9);
return [str.slice(0, 6) + ' ' + flightNumber]
}
console.log(...addSpace('flight843'));
You can match 6 characters a-z and 3 or more digits using a pattern with 2 capture groups.
In the replacement use the 2 capture groups with a space in between.
const addSpace = str => str.replace(/\b([a-z]{6})(\d{3,})\b/g, "$1 $2");
console.log(addSpace('flight843'));
You can also literally match flight, and append anchors if that is the only allowed string.
^(flight)(\d{3,})$
As flight string will always be there. We can simply achieve this by using String.replace() method. I also done the performance test in jsbench and it runs fastest among all the solutions mentioned here.
Live Demo :
const addSpace = function (str) {
const len = str.replace('flight', '').length;
return len > 3 ? str.replace('flight', 'flight ') : str
}
console.log(addSpace('flight843')); // 'flight843'
console.log(addSpace('flight8432')); // 'flight 8432'
If you need only addSpace I belived this is a simple solution for your quest. With this dynamic function is possible add Space for many block of words.
/* ADD Spacing */
const string = "flightNumber";
const dataValue = "flight";
function addSpacing(str, data){
//Verify if exist the wolrd in the string
if(str.includes(data)){
//get the word
let word = str.substr(0, data.length);
//Add Capitalise
let strCapitalize = word.charAt(0).toUpperCase();
let cleanword = word.slice(1, +data.length);
//add spacing
let newStr = str.replace(word, strCapitalize + cleanword + " ");
console.log(newStr);
}
}
addSpacing(string, dataValue);