Home > Software design >  How to insert white space before the last two character of the string
How to insert white space before the last two character of the string

Time:08-24

var a = abadswdFS output = abadswd FS

there might be many character in the front but space need to be added before the last two character in typescript

CodePudding user response:

var a = "abadswdFS";

const firstPart = a.slice(0, -2);
const secondPart = a.slice(-2);
const output = firstPart   " "   secondPart;

console.log(output);

CodePudding user response:

You can use regex to handle the cases when the string is shorter than 3 characters or there's already a space

var inputs = [
 'abadswdFS',
 'f',
 'fs',
 'abadswd FS'
]

function addSpaceBeforeLastTwoCharacters(str) {
  return str.replace(/^(. ?)((?<!\s)\w{2})$/, '$1 $2')
}

console.log(inputs.map(addSpaceBeforeLastTwoCharacters))

CodePudding user response:

One of many possible solutions.

let string = "teststring";

if(string.length > 2) {
  string = string.substring(0, string.length - 2)   ' '   string.substring(string.length -2);
}

console.log(string)

CodePudding user response:

If only the position in the string matters you can use the substring-method in combination with the length-property. Example:

const inputVar = 'abadswdFS' 
const outputVar = inputVar.substring(0,inputVar.length-3)   ' '   inputVar.substring(inputVar.length-2, inputVar.length)

console.log(outputVar)

  • Related