2011-09-13 83 views
0

我一直在研究一个函数,将单词之间的空格变为字符串" "(空格)。字符串操作,用(空格)替换“”空格

例如,"Hello World. Hi there."将成为"Hello(space)world.(space)Hi(space)there."

编辑:我试图建立这样一组特定的结构化英语的是如下:

  • 结果的初始值设置为空字符串
  • 在参数字符串
  • 每个索引如果该索引的字符是空格然后
  • 追加“(空格)”导致
  • 其他
  • 该索引处添加字符导致
  • 结束时,如果
  • 年底为
  • 返回结果

这是我能到目前为止。:

function showSpaces(aString) 
{ 
var word, letter; 

word = aString 
for var (count = 0; count < word.length; count = count + 1) 

{ 
    letter = word.charAt(count); 
    if (letter == " ") 
    { 
     return("(space)"); 
    } 
    else 
    { 
     return(letter); 
    } 
} 
} 

每当我测试这个函数调用,什么都没有发生:

<INPUT TYPE = "button" NAME = "showSpacesButton" VALUE ="Show spaces in a string as (space)" 
     ONCLICK = "window.alert(showSpaces('Space: the final frontier'));"> 

我刚刚从JavaScript开始。任何帮助,将不胜感激。

-Ross。

+0

没有必要t o在标题中加入焦点话题。 StackOverflow将在页面的标题前加上最受欢迎的标签(在本例中为JavaScript)。 – 2011-09-13 19:37:35

+0

http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – 2011-09-13 19:38:01

回答

3

使用String.replace

function showSpaces(aString) 
{ 
    return aString.replace(/ /g,'(space)'); 
} 

编辑:让你的代码工作:

function showSpaces (aString) 
{ 

    var word, letter, 
     output = ""; // Add an output string 

    word = aString; 
    for (var count = 0; count < word.length; count = count + 1) // removed var after for 

    { 
     letter = word.charAt(count); 
     if (letter == " ") 
     { 
      output += ("(space)"); // don't return, but build the string 
     } 
     else 
     { 
      output += (letter); // don't return, but build the string 
     } 
    } 
    return output; // once the string has been build, return it 

} 
+0

感谢这个伟大的解决方案。我唯一的问题是,我试图按照一套特定的结构化英语来构建它。 结果的初始值设置为空字符串 在参数字符串 每个索引如果该索引的字符是空格然后 追加“(空格)”,导致 别的 该索引来在追加字符结果 结束如果 结束为 返回结果 –

+0

@Ross,我已经更新了算法中的注释。让我知道这是否有帮助。 – Joe

+0

非常感谢。这些评论真的很有帮助! –

1

没有, “无” 不会发生。它很少。会发生什么情况是您在代码中出现语法错误,因为您使用的是for var (而不是for (var

如果解决该问题,您会注意到只会得到字符串中的第一个字符,因为在循环中使用return而不是将字符串放在一起并在循环后返回。

你可以这样做:

function showSpaces(word) { 
    var letter, result = ""; 
    for (var count = 0; count < word.length; count++) { 
    letter = word.charAt(count); 
    if (letter == " ") { 
     result += "(space)"; 
    } else { 
     result += letter; 
    } 
    } 
    return result; 
} 

演示:http://jsfiddle.net/Guffa/pFkhs/

(注:使用+=连接字符串的长字符串表现不好)

您还可以使用正则表达式替换字符串:

function showSpaces(word) { 
    return word.replace(/ /g, "(space)"); 
} 
+0

您提出的一个观点:“没有事情没有发生”。我应该更仔细地看待事情。非常感谢您的导师解释我的“回报”。在循环中也是如此。这是非常宝贵的。 –