mirror of
https://github.com/iib0011/omni-tools.git
synced 2025-12-18 02:06:30 +00:00
- Changed the replaceText method to take all options as arguments. - Removed compute from SimpleRadio component. - Moved InitialValuesType type and initialValues object to a separate file to avoid Fast Refresh error. - Used ToolContent and added usage examples.
41 lines
1.2 KiB
TypeScript
41 lines
1.2 KiB
TypeScript
import { InitialValuesType } from './initialValues';
|
|
|
|
function isFieldsEmpty(textField: string, searchField: string) {
|
|
return !textField.trim() || !searchField.trim();
|
|
}
|
|
|
|
export function replaceText(options: InitialValuesType, text: string) {
|
|
const { searchValue, searchRegexp, replaceValue, mode } = options;
|
|
|
|
switch (mode) {
|
|
case 'text':
|
|
if (isFieldsEmpty(text, searchValue)) return text;
|
|
return text.replaceAll(searchValue, replaceValue);
|
|
case 'regexp':
|
|
if (isFieldsEmpty(text, searchRegexp)) return text;
|
|
return replaceTextWithRegexp(text, searchRegexp, replaceValue);
|
|
}
|
|
}
|
|
|
|
function replaceTextWithRegexp(
|
|
text: string,
|
|
searchRegexp: string,
|
|
replaceValue: string
|
|
) {
|
|
try {
|
|
const match = searchRegexp.match(/^\/(.*)\/([a-z]*)$/i);
|
|
|
|
if (match) {
|
|
// Input is in /pattern/flags format
|
|
const [, pattern, flags] = match;
|
|
return text.replace(new RegExp(pattern, flags), replaceValue);
|
|
} else {
|
|
// Input is a raw pattern - don't escape it
|
|
return text.replace(new RegExp(searchRegexp, 'g'), replaceValue);
|
|
}
|
|
} catch (err) {
|
|
console.error('Invalid regular expression:', err);
|
|
return text;
|
|
}
|
|
}
|