UNPKG

ice.fo.utils

Version:

315 lines (255 loc) 8.25 kB
import _get from 'lodash/get' import qs from 'qs' /** * Doc: https://stackoverflow.com/questions/190852/how-can-i-get-file-extensions-with-javascript "" --> "" "name" --> "" "name.txt" --> "txt" ".htpasswd" --> "" "name.with.many.dots.myext" --> "myext" */ export function getFilePathExtension (text) { return text.slice((text.lastIndexOf('.') - 1 >>> 0) + 2) } /** * Parse inline styles string to object * * Ex: "display: block; width: 100%;" => { display: 'block'; width: '100%' } * @param {*} text * @returns */ export function convertToStylesObject (text) { if (!text || !text.split) { return {} } text = text.replace(/(?:\r\n|\r|\n)/g, ';') text = text.replace(/\{|\}/g, '') const result = text.split(';').filter(i => !!i.trim() && i.includes(':')).reduce(function (ruleMap, ruleString) { const [left, right] = ruleString.split(':') const attribute = left.trim().replace(/-(.)/g, (match, group1) => group1.toUpperCase()) ruleMap[attribute] = right.trim() return ruleMap }, {}) return result } /** * Ex: replaceAll("find text to replace with text", "text", "Nikochin") => "find Nikochin to replace with Nikochin" * @param {*} text String input * @param {*} find String to find * @param {*} by String to replace with */ export function replaceAll (text, find, by) { return text.replace(new RegExp(escapeRegExp(find), 'g'), by) } /** * Ex: formatString({ username: "Nikochin" }, "{username} comes to rescue") => "Nikochin comes to rescue" * @param {*} target Object contains values * @param {*} pattern String input */ export function formatStringValue (target, pattern, funcs = {}, prefix = '{', suffix = '}') { // const regExp = /{([^}]*)}/g // "get content {test}" => "{test}"" // const regExp = /[^{}]+(?=})/g // "get between content {test}" => "test" // const matches = pattern.match(regExp) const matches = getStringBetweenCharacters(pattern, prefix, suffix) if (!matches) { return pattern } let result = pattern matches.forEach((match) => { const find = prefix + match + suffix const parts = match.replace(/\s/g, '').split(/\|/) let value = _get(target, parts[0]) if (parts.length > 1) { for (let i = 1; i < parts.length; i++) { value = funcs[parts[i]] ? funcs[parts[i]](value) : value } } result = replaceAll(result, find, value) }) return result } /** * Find and return list of string that enclosed between [left] and [right] characters * * Ex: getStringBetweenCharacters('The {brown} fox jump over the {box}.', '{', '}') * * => [brown, box] * * @param {string} text * @param {string} left * @param {string} right * @returns */ export function getStringBetweenCharacters (text, left, right) { // const suffix = right.slice( -1 ); // const regex = new RegExp( `(?<=${ left }).+?(?=${ right }(?!${ suffix }))`, 'g' ); // const matches = text.match( regex ); // // return matches; // For IE support const leftIndex = text.indexOf(left) if (leftIndex == -1) { return [] } const rightIndex = text.indexOf(right) if (rightIndex == -1) { return [] } return [text.substring(leftIndex + left.length, rightIndex)].concat(getStringBetweenCharacters(text.substr(rightIndex + right.length), left, right)) } export function formatStringBlocks (text, blocks = [3, 4, 4], delimiter = '-') { return blocks.reduce((result, length) => { if (text.length) { const part = text.substr(0, length) text = text.substr(length) result.push(part) } return result }, []).join(delimiter) } export function escapeRegExp (string) { return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') } export function getKoreanCharacters (text) { return text.replace(/[a-zA-Z0-9$&+,:;=?@#|'<>.^*()%!-]/g, '') // Can change to improve } export function getNonKoreanCharacters (text) { return text.replace(/[^a-zA-Z0-9$&+,:;=?@#|'<>.^*()%!-]/g, '') // Can change to improve } /** * Korean is 2 bytes each character * Else 1 byte * * @param {*} text */ export function countSimpleStringBytes (text) { const koreanChars = getKoreanCharacters(text) const nonKoreanChars = getNonKoreanCharacters(text) return koreanChars.length * 2 + nonKoreanChars.length } /** * Format Korean Mobile */ export function formatMobileText (text) { const blocks = [3, 4, 4] const delimiters = '-' return formatStringBlocks(text, blocks, delimiters) } /** * Format Korean Tel */ export function formatTelText (text) { let blocks = [] const delimiters = '-' if (text.startsWith('02')) { if (text.length >= 10) { blocks = [2, 4, 4] } else { blocks = [2, 3, 4] } } else if (text.length >= 11) { blocks = [3, 4, 4] } else { blocks = [3, 3, 4] } return formatStringBlocks(text, blocks, delimiters) } export function getNumbericTexts (text) { return text.match(/\/\d+/g) || [] } export function getNumberTextOnly (text) { if (!text) { return '' } if (typeof text != 'string') { return text } return text.replace(/\D/g, '') } export function addParamsToUrl (text, obj) { if (!text || !Object.keys(obj).length) { return text || '' } if (!text.includes('?')) { text += '?' } const qi = text.indexOf('?') const params = qs.parse(text.substr(qi + 1)) const query = qs.stringify({ ...params, ...obj }) return text.substr(0, qi) + (query ? '?' + query : '') // if (!text.includes('?')) { // text += '?' // } // for (const k in obj) { // const v = obj[k] // const key = encodeURIComponent(k) // const value = encodeURIComponent(v) // // kvp looks like ['key1=value1', 'key2=value2', ...] // const kvp = text.substr(text.indexOf('?') + 1).split('&') // let i = 0 // for (; i < kvp.length; i++) { // if (kvp[i].startsWith(key + '=')) { // const pair = kvp[i].split('=') // pair[1] = value // kvp[i] = pair.join('=') // break // } // } // if (i >= kvp.length) { // kvp[kvp.length] = [key, value].join('=') // } // // can return this or... // const params = kvp.join('&') // return text.substr(0, text.indexOf('?')) + params // } } /** * http://localhost:8080/productImage/file/202110/06/e84739fa-757e-4f93-a0e1-2e2780cbe5db.png/09.sample_thum01.png * -> * http://localhost:8080/productImage/file/202110/06/e84739fa-757e-4f93-a0e1-2e2780cbe5db.png */ export function getFilePathFromStorePath (value) { if (!value) { return value } const checkUrl = value.substr(0, value.lastIndexOf('/')) if (/\.[0-9a-z]{3,4}$/.test(checkUrl)) { return checkUrl } return value } /** * width: 300 * height: 0 * http://localhost:8080/productImage/file/202110/06/e84739fa-757e-4f93-a0e1-2e2780cbe5db.png/09.sample_thum01.png * -> * http://localhost:8080/image/productImage/file/202110/06/300/0/e84739fa-757e-4f93-a0e1-2e2780cbe5db.png */ export function getResizeImagePath ({ value, width = 0, height = 0 }) { if (!value) { return value } const filePath = getFilePathFromStorePath(value) const supportExtensions = ['.png', '.jpg', '.jpeg'] if (!supportExtensions.some(i => filePath.includes(i) || filePath.includes(i.toUpperCase()))) { return filePath } const domainRegex = /(^([a-z]{3,5})?(:)?\/\/)((.*?)\/)/g const dateRegex = /\/\d{6}\/\d{2}\//g const [domain] = filePath.match(domainRegex) || [] const [date] = filePath.match(dateRegex) || [] if (!domain || !date) { return filePath } return filePath.replace(domain, domain + 'image/').replace(date, date + `${width}/${height}/`) } export function convertToQueryObject ({ text, data, parsePrefix = '#{', parseSuffix = '}' }) { try { const result = qs.parse(text) for (const k in result) { result[k] = formatStringValue(data, result[k], undefined, parsePrefix, parseSuffix) } return result } catch (error) { console.error(error) return {} } } export function getFilename ({ text, keepExtension = false }) { const name = text.split('\\').pop().split('/').pop() return keepExtension ? name : name.split('.')[0] }