Answer the question
In order to leave comments, you need to log in
How to make a regular expression to replace a letter in a string with keys from an object?
There is a string with English text and there is an object whose keys are English letters, and the values are letters of another alphabet.
The application has buttons that in the original text replace letters when pressed. Now it looks like thisconst pairs = { "a": "ა", "b": "ბ", "g": "გ", ...}
let myObject = { a: "ა", b: "ბ", g: "გ", ... } // Сюда пушаем новую пару при нажатии кнопки
let text = "There are many ways that reading helps you to learn English...."
class App extends Component {
render() {
Object.keys(myObject).map((key, index) => {
var search_term = new RegExp(key, "gi")
text = text.replace(search_term, myObject[key]) // хочу заменить на регулярку, в которую смогу добавлять и убирать пары букв
})
return (
<div className="App-body">
<p>{text}</p>
</div>
)
}
}
Answer the question
In order to leave comments, you need to log in
It is possible without a regular expression:
const pairs = { a: 'ა', b: 'ბ', g: 'გ'};
const str = 'There are many ways that reading helps you to learn English.';
[...str].map(letter => pairs[letter.toLowerCase()] || letter).join``;
const pairs = { a: 'ა', b: 'ბ', g: 'გ'};
const str = 'There are many ways that reading helps you to learn English.';
str.replace(RegExp(Object.keys(pairs).join('|'), 'gi'), letter => pairs[letter.toLowerCase()]);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question