Javascript中的实时摩尔斯电码转换器 [英] Real Time Morse code converter in Javascript

查看:165
本文介绍了Javascript中的实时摩尔斯电码转换器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在看到谷歌愚蠢的莫尔斯代码gmail笑话之后,我想我会尝试在javascript中创建一个实时莫尔斯代码转换器。

After seeing Google's april fools joke of the morse code gmail, I thought I'd try to create a real-time morse code converter in javascript.

我'使用正则表达式并替换以将莫尔斯代码更改为字符。例如:

I'm using regex and replace to change the morse code into character. For example:

.replace(/.- /g, "a").replace(/.-. /g, "r")

我遇到的问题是当我输入 .-。对于r,它给我一个a,因为它首先看到 .-
如何才能让它只替换完全匹配?

The issue I'm having is that when I'm typing .-. for "r" it give me an "a" because it sees .- first. How can I make it replace only exact matches?

更新并正常工作!!感谢每一位帮助我的人

Updated and working!! Thanks to every one that helped me

http: //jsfiddle.net/EnigmaMaster/sPDHL/32/ - 我的原始代码

http://jsfiddle.net/EnigmaMaster/sPDHL/32/ - My Original code

http://jsfiddle.net/EnigmaMaster/LDKKE/6/ - 由Shawn Chin改写

http://jsfiddle.net/EnigmaMaster/LDKKE/6/ - Rewritten by Shawn Chin

< a href =http://jsfiddle.net/EnigmaMaster/y9A4Y/2/ =nofollow> http://jsfiddle.net/EnigmaMaster/y9A4Y/2/ - 由Matthias Tylkowski改写

http://jsfiddle.net/EnigmaMaster/y9A4Y/2/ - Rewritten by Matthias Tylkowski

如果有人有其他方式撰写此计划,请发布 JsFiddle

If anyone has other ways of writting this program please post a JsFiddle

我很想知道如何做到这一点

Id love to see how else this can be done

推荐答案

其他答案已经涵盖了你的例子没有工作的原因所以我不会重复它们。

The other answers have already covered the reasons why your example was not working so I'll refrain from repeating them.

但是,我可以建议,因为你已经使用了空格划分每个代码,一个直t-forward解决方案是做一个简单的 .split()来将输入文本分段为单个单元,然后简单地将代码一对一映射到字符。
这比重复的正则表达式替换更有效,并且不容易出错。

However, may I suggest that since you're already using spaces to delimit each code, a straight-forward solution would be to do a simple .split() to segment the input text into individual units then simply do a one-to-one mapping of code to chars. This will be a lot more efficient than repeated regex replacements and less prone to errors.

例如:

var morse = {  // use object as a map
    '.-': 'a', 
    '-...': 'b', 
    '-.-.': 'c', 
    // .... the rest ...
};

function translate_morse(code) {  // given code, return matching char
    return (typeof morse[code] === "undefined") ? "" : morse[code];
    // if the var is not found, the code is unknown/invalid. Here we 
    // simply ignore it but you could print out the code verbatim and use
    // different font styles to indicate an erroneous code
}

// example usage
translated = code_text.split(" ").map(translate_morse).join("");

这是一个有效的例子: http://jsfiddle.net/KGVAm/1/

Here's a working example: http://jsfiddle.net/KGVAm/1/

ps我冒昧地调整了代码和行为,即禁用其他字符的输入,但允许backscape允许更正。

p.s. I've taken the liberty of tweaking the code and the behaviour a little, i.e. disabling the input of other chars but allowing backscape to allow corrections.

这篇关于Javascript中的实时摩尔斯电码转换器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆