sigit.io/src/utils/string.ts

40 lines
1.3 KiB
TypeScript
Raw Normal View History

export const shorten = (str: string, offset = 9) => {
// return original string if it is not long enough
if (str.length < offset * 2 + 4) return str
return `${str.slice(0, offset)}...${str.slice(
str.length - offset,
str.length
)}`
}
export const stringToHex = (str: string) => {
// Convert the string to an array of UTF-16 code units using the spread operator
const codeUnits = [...str]
// Map each code unit to its hexadecimal representation
const hexChars = codeUnits.map((codeUnit) => {
// Convert the code unit to its hexadecimal representation with leading zeros
const hex = codeUnit.charCodeAt(0).toString(16).padStart(2, '0')
return hex
})
// Join the hexadecimal characters into a single string
const hexString = hexChars.join('')
// Return the resulting hexadecimal string
return hexString
}
export const hexToString = (hex: string) => {
// Split the hex string into pairs of two characters
const pairs = hex.match(/.{1,2}/g) || []
// Convert each pair from hexadecimal to its decimal equivalent,
// then convert each decimal value to its character representation
const chars = pairs.map((pair) => String.fromCharCode(parseInt(pair, 16)))
// Join the resulting characters into a single string
return chars.join('')
}