Achs98
Achs98

Reputation: 51

Dynamic replacement of Latin letters to Cyrillic letters as they're typed in JavaScript

I'm trying to build this program which needs the input part to be similar to google-translate's. that is, Latin letters are dynamically replaced into Cyrillic letters as they're typed (like, when letter B is keyed, the letter Б is printed in the input box and so on)

I tried linking the latin letters to cyrillic letters through onkeyup events, but some letters like Sh(Ш) or Ya(Я) are associated to key-combinations and I can't find a way around it. I'd include the code sample I had already tried out but the problem I have is more of a plan related one than implement related one. It'd be great if I can get help to figure out how to tackle and build this.

TIA

Upvotes: 0

Views: 1174

Answers (2)

Massaynus
Massaynus

Reputation: 452

const map = {
  'b': 'Б', //...etc
}

function onPressHandler(e) {
  const value = e.target.value 
  //alternatively you could handle each pressed key at a time

  const length = value.length
  let output = ''

  for (let i = 0; i < length; i++)
    output += map[value.chatAt(i)]

  e.target.value = output // if you want or just return it


}

Upvotes: 1

The Bomb Squad
The Bomb Squad

Reputation: 4337

I'm bored so I coded up an example(proof of concept)
I keep determine what the normal text is, and what the converted text is, and that is what allows multiple key combinations(looking at the entire string not just per key input)

var _change={sh:'lol',ab:'cd',a:'z',SH:'LOL',AB:'CD',A:'Z'} //largest strings first
var _default={lol:'sh',cd:'ab',z:'a',LOL:'SH',CD:'AB',Z:'A'} //largest strings first
//you can fill these objects with as many translations as you want
//if a smaller string was first, "ab" would turn to "zb" before it can turn into "cd"
//make sure the every translation text is different from any original text
var _text=document.getElementById('text')
let defaultText=(text)=>text.split('').map(l=>_default[l]||l).join('')
let changeText=(text)=>{
  Object.keys(_change).forEach(toSplit=>text=text.split(toSplit).join(_change[toSplit]))
  return text
}
setInterval(()=>{
  let text=_text.value
  _text.value=changeText(defaultText(text))
},300)
<input id="text" />
<p>I only have 3(technically 6) examples.. <i>'sh' to 'lol'</i>, <i>'a' to 'z'</i> and <i>'ab' to 'cd'</i>
<br><p>technically 6 because I also have <i>'SH' to 'LOL'</i> and so forth

Upvotes: 1

Related Questions