javascript - jQuery:在文本区域段落中查找单词并将其替换为单词

标签 javascript php jquery mysql ajax

我正在尝试将文本/段落从其原始英文版本翻译成山谷女孩的谈话。例如,“嗨”将是“hellloooooo,怎么了?”。这些单词已与英文单词及其翻译的 Valley Girl 版本一起输入数据库。示例:英语栏-> hi,VG 栏-> hellloooooo,英语-> yes,VG -> like,hells yes

我正在使用 MySQL 从数据库中获取翻译后的单词并返回 json。

这就是我在 AJAX 中检索它的方式:

$.ajax({
    type: "GET",
    url: "dictionary.php",
    success: function(data) {
        var json = JSON.parse(data);
        // replacing all the ing's with in'
        $("#textarea").each(function(){
            var ing = $(this).val().replace(/ing/g,"in'");
            $(this).val(ing);
            // finding the English words and replacing with VG 
            $.each(json, function(idx, obj) {
                var vg= $("#content").val().replace(/obj.english/g, obj.vg);
                $("#textarea").val(vg);
            );
        });                 
    }
});

我把“ing”替换得很好并且工作正常,但试图替换山谷女孩的话是行不通的。我是否错误地循环了 json 对象?

编辑:这是 json 数据

[{"english":"hi","0":"hi","vg":"hellloooooo!","1":"hellloooooo"},    {"english":"yes","0":"yes","vg":"like, hells yes","1":"like, hells yes"},.....]

最佳答案

请参阅这个替换单词的小示例,然后将其输出到新字段,这可能有助于您实现想要的目标。

它会循环遍历每个单词并进行精确的单词匹配,如果某些翻译也包含英语单词,您可能会遇到问题

$(document).ready(function(){
  
 var json = [{"english":"hi","0":"hi","vg":"hellloooooo!","1":"hellloooooo"},    {"english":"yes","0":"yes","vg":"like, hells yes","1":"like, hells yes"}];

var userInput = $('#textarea').val();

json.forEach(function(word){
  console.log(word);
  userInput = userInput.replace(new RegExp("\\b"+word.english+"\\b","g"),word.vg);
});
  $('#translation').val(userInput);
});
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <textarea id="textarea">
    hi this is a test of yes translation. hi yes
  </textarea>
  <textarea id="translation">
  
  </textarea>
  </body>
</html>

关于javascript - jQuery:在文本区域段落中查找单词并将其替换为单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35832853/

相关文章:

Javascript href 刷新 iframe 不起作用

Javascript 灯箱无法在 html 部分标签内运行

php - 我如何向新注册用户发送确认电子邮件?

javascript - 电子邮件验证不起作用

jquery - 将 javascript getElementsByName 转换为 Jquery

javascript - 更改背景图像时平滑淡入淡出

javascript - 在新生成的元素上附加数据

javascript - karma-html2js 不会创建 window.__html__

php - 如何进行不区分大小写的搜索

php - xslt 1 和求和函数