N
N
Ninja Mate2019-02-07 14:26:04
JavaScript
Ninja Mate, 2019-02-07 14:26:04

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 this
const 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>
    )
  }
}

How to make such a routine?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Z
zendor, 2019-02-07
@zendor

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``;

Well, or with him:
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 question

Ask a Question

731 491 924 answers to any question