简体   繁体   English

基本的Javascript字符串操作

[英]Basic Javascript String Manipulation

Hello there everyone, 大家好

I've been trying to figure out how to create a function that takes any input and adds spaces to it before returning it. 我一直试图弄清楚如何创建一个函数,该函数接受任何输入并在返回之前添加空格。 For example. 例如。 The function would change "hello" into "hello" When I perform the task -not- as a function, it seems to work okay. 当我将任务(而不是功能)执行时,该功能会将“ hello”更改为“ hello”,看来可以正常工作。 I previously had some good feedback about using the split() and join() functions and that seems to get the desired effect. 以前,我对使用split()和join()函数有一些好的反馈,这似乎获得了预期的效果。

It just doesn't seem to be working as a function. 它似乎并没有发挥功能。 Here is the code that I have come up with so far: 这是到目前为止我提出的代码:

function sStr(aString)
{   
    var mySplitResult = aString.split("").join(" ");
    return mySplitResult;  
}
window.alert(sStr(test));

I would really appreciate any help with this as I'm racking my brains trying to learn this stuff. 我会竭尽全力尝试学习这些东西,对此我将非常感谢。 I can see that I still have a long way to go. 我看到我还有很长的路要走。

test周围加上引号,例如:

alert(sStr("test"));

In your code, test is not a string, but a variable. 在您的代码中,test不是字符串,而是变量。 Strings need to be inserted in quotes or double quotes. 需要在双引号或双引号中插入字符串。

function sStr(aString)
{   
    return aString.split("").join(" ");
}
window.alert(sStr('test'));

Check this fiddle . 检查这个小提琴

It works, just add quotes around test : 它有效,只需在test周围添加引号:

function sStr(aString)
{   
    var mySplitResult = aString.split("").join(" ");
    return mySplitResult;  
}
window.alert(sStr("test"));

It looks your function works beautifully. 看起来您的功能运作精美。 In this line: 在这一行:

window.alert(sStr(test));

Is test a variable, or did you mean to provide a string: test变量,还是要提供一个字符串:

window.alert(sStr('test'));

While we're at it, you may want to make your function handle the cases where the (1) parameter is undefined or null and (2) the parameter is not a string (eg: numbers): 当我们使用它时,您可能想让您的函数处理以下情况:(1)参数未定义或为null并且(2)参数不是字符串(例如:数字):

function sStr(aString)
{   
    if(!aString)
    {
        return "";
    }

    var mySplitResult = aString.toString().split("").join(" ");
    return mySplitResult;  
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM