所以我在文本区域中写了一个句子,我在那里使用API发送它进行任何拼写检查,这会返回一个JSON拼写错误的单词,那么我如何替换基于句子的单词关于词索引?
我正在使用AngularJS 1和Javascript
示例:
"在出版,艺术和传播方面,内容是指向"
的信息和体验。
当我发送到服务器时,它输出:
{"4":"communication","8":"information"}
textarea需要的输出为:
"在出版,艺术和传播方面,内容是指向"
的信息和体验。
ANGULAR JS CODE:
<div class="form-group">
<textarea class="form-control" id="exampleFormControlTextarea1"
rows="10" ng-model="textcontent" required>
</textarea>
</div>
var myApp = angular.module('myApp', []);
myApp.controller('myCtrl', function($scope,$http) {
$scope.dataautocorrect = {
"data":$scope.textcontent
}
$http.post(autocorrect,JSON.stringify($scope.dataautocorrect)).then(function (res){
$scope.response = res.data;
console.log(res);
console.log( "Auto corrected Data");
});
}
那么如何根据JSON Word索引替换拼写错误呢?
答案 0 :(得分:1)
您可以使用正则表达式将单词拆分为数组,然后替换特定索引
上的单词//your string value from the textarea
var yourString = "In publishing, art, and communicatio, content is the inforation and experiences that are directed towards ";
//find the words in the string
var words = yourString.match(/\b(\w+)\b/g);
//words will then contain ["In", "publishing", "art", "and", "communicatio", "content", "is", "the", "inforation", "and", "experiences", "that", "are", "directed", "towards"]
//results from the spelling check api
var correctWords = {"4":"communication","8":"information"};
//loop through the keys in the json object and replace the misspelled word with the corrected word
Object.keys(correctWords).forEach(function(key) {
var wordToReplace = words[key];
yourString = yourString.replace(wordToReplace, correctWords[key]);
});