#javascript #regex #function #object
#javascript #регулярное выражение #функция #объект
Вопрос:
Я работаю над функцией, которая находит prop объектов, который соответствует строке внутри […] и заменяет значением prop .. он также должен игнорировать любые строки внутри [[…]] и удалять внешние квадратные скобки
Например
интерполировать(‘Hello [name] [[author]]’, {name: ‘foo’, author: ‘bar’})
Приведет к появлению «Hello foo [автор]»
Вот мой код на данный момент
const person1 = { name: 'John', author: 'John amp; John'};
const person2 = { name: 'Jill', author: 'Jk Jowling' };
const person3 = { name: 'Jack', author: 'Wacko Jacko'};
const str1 = 'Hello [name] [[author]]';
// Find the objects prop that matches the string inside [...] and replace with the value of the prop
// Ignore the values inside double brackets [[...]]
const interpolate = (string, obj) => {
// Throw errors if incorrect arguments are passed in
if (!string || typeof string !== 'string') {
throw new Error(`"string" is required`);
}
if (!obj || typeof obj !== 'object') {
throw new Error(`"object" is required`);
}
Object.keys(obj).map((value) => {
string
.split(' ')
.indexOf(`[${value}]`) === 1 || string.indexOf(`[[${value}]]`) === -1
? console.log(string.replaceAll(`[${value}]`, obj[value]))
: console.log(`One or more unidentifiers found in String: ${string}`)
})
// Working better but still need to work on conditionals
// Removed RegEx
// Used replaceAll to target multiple [string]
};
interpolate(str1, person1);
interpolate(str1, person2);
interpolate(str1, person3);
Ответ №1:
Вы могли бы использовать регулярное выражение
(?<![)[([^[]]*)](?!])
Демонстрация регулярных выражений
Это приведет к получению всех строк , []
которым не предшествует a [
и за которыми следует a ]
. ([^[]]*)
Часть передаст строку внутри []
в группу захвата. Вы можете использовать второй параметр из функции replacer, чтобы получить к нему доступ и получить значение из объекта.
Замените соответствующую строку свойством из объекта
function interpolate (string, obj) {
return string.replace(/(?<![)[([^[]]*)](?!])/g, (m, p1) => obj[p1] ?? '')
}
const str = 'Replace name: [name] but not [[author]]. Replace this with author: [author]';
console.log(
interpolate(str, { name: 'John', author: 'John amp; John'})
)
console.log(
interpolate(str, { name: 'Jill', author: 'Jk Jowling' })
)