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. I previously had some good feedback about using the split() and join() functions and that seems to get the desired effect.
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. 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 :
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:
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):
function sStr(aString)
{
if(!aString)
{
return "";
}
var mySplitResult = aString.toString().split("").join(" ");
return mySplitResult;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.