Javascript .replace()的问题
我正在尝试删除一个带有空格的字符串中的所有“,”。目前,我有以下代码,其中tweettxt只是一个包含多个hello和bye实例的数组:Javascript .replace()的问题,javascript,regex,Javascript,Regex,我正在尝试删除一个带有空格的字符串中的所有“,”。目前,我有以下代码,其中tweettxt只是一个包含多个hello和bye实例的数组: // function for getting the frequency of each word within a string function getFreqword(){ var string = tweettxt.toString(), // turn the array into a string split = string.s
// function for getting the frequency of each word within a string
function getFreqword(){
var string = tweettxt.toString(), // turn the array into a string
split = string.split(" "), // split the string
words = {};
for (var i=0; i<split.length; i++){
if(words[split[i]]===undefined){
words[split[i]]=1;
} else {
words[split[i]]++;
}
}
return words;
}
在尝试删除“bye,hello”的出现时,我在第4行遇到并实现了.replace而不是.splitsplit=string.replace(/,/g,“”)
,但是这会返回:
{ h: 56, e: 98, l: 112, o: 56, ' ': 91, b: 42, y: 42 }
我的理解是.replace只会将,替换为“”,但情况显然不是这样。有人能提供帮助吗
编辑:
用编码。替换
// function for getting the frequency of each word within a string
function getFreqword(){
var string = tweettxt.toString(), // turn the array into a string
split = string.replace(/,/g, ""), // split the string
words = []; // array for the words
for (var i=0; i<split.length; i++){
if(words[split[i]]===undefined){
words[split[i]]=1;
} else {
words[split[i]]++;
}
}
return words;
}
//用于获取字符串中每个单词的频率的函数
函数getFreqword(){
var string=tweettxt.toString(),//将数组转换为字符串
split=string。替换(/,/g,“”,//拆分字符串
words=[];//单词的数组
for(var i=0;istring.replace(/,/g,“”)只返回不带逗号的相同字符串(不是数组)。
此外,如果需要计算基于od空格的单词数,则应将逗号替换为空格(“”)。
因此,您需要先替换逗号,然后进行拆分。
例如:
函数getFreqword(){
var string=tweettxt.toString(),//将数组转换为字符串
sanitizedString=string.replace(/,/g,“”),
split=sanitizedString.split(“”),//拆分字符串
单词={};
对于(var i=0;isplit
返回一个数组,replace
返回一个字符串,因此您必须相应地调整您的逻辑。您到底在哪里尝试将此.replace()
代码放入您的代码中?请在问题中适当地显示它。.replace()
对字符串进行操作并返回一个新的字符串对象。使用字符串和拆分等词作为变量名不是一个好做法。您不能直接使用tweettxt吗?请准确显示输入内容和所需输出内容。您的问题不是很清楚,请非常清楚什么是字符串,什么是对象或数组。我希望返回{hello:50,bye:36,'bye,hello':6},不带'bye,hello'元素。输入在问题中陈述,简单且多个hello's和bye's的数组,不包括,因为它是一个长数组,需要一个符咒,谢谢
// function for getting the frequency of each word within a string
function getFreqword(){
var string = tweettxt.toString(), // turn the array into a string
split = string.replace(/,/g, ""), // split the string
words = []; // array for the words
for (var i=0; i<split.length; i++){
if(words[split[i]]===undefined){
words[split[i]]=1;
} else {
words[split[i]]++;
}
}
return words;
}
function getFreqword(){
var string = tweettxt.toString(), // turn the array into a string
sanitizedString = string.replace(/,/g, " "),
split = sanitizedString.split(" "), // split the string
words = {};
for (var i=0; i<split.length; i++){
if(words[split[i]]===undefined){
words[split[i]]=1;
} else {
words[split[i]]++;
}
}
return words;
}