使用 Javascript (NodeJS) 进行字符串操作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10338357/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
String manipulation with Javascript (NodeJS)
提问by quarks
I'm trying to remove the first 13 characters of a string with this code:
我正在尝试使用以下代码删除字符串的前 13 个字符:
requestToken = requestToken.substring(13);
However, I'm getting "has no method substring
" error with NodeJS, the code above that mostly recommended in the Javascript forums does not work with NodeJS?
但是,我在has no method substring
使用 NodeJS 时遇到“ ”错误,上面在 Javascript 论坛中主要推荐的代码不适用于 NodeJS?
回答by ControlAltDel
it seems like requestToken may not be a string.
看起来 requestToken 可能不是字符串。
Try
尝试
requestToken = '' + requestToken;
and then requestToken.substring(13);
然后 requestToken.substring(13);
回答by Nevir
substring
(and substr
) are definitely functions on the string prototype in node; it sounds like you're not dealing with a string
substring
(和substr
) 绝对是节点中字符串原型上的函数;听起来你不是在处理字符串
$ node
> "asdf".substring(0,2)
'as'
回答by Elliot Bonneville
Convert requestToken
to a string first:
首先转换requestToken
为字符串:
requestToken = (requestToken+"").slice(13);
回答by Alex Wayne
requestToken
must not be a string then. It's likely some sort of object, and the string you want is likely returned by a method on, or a property of, that object. Try console.log(requestToken)
and see what that really is.
requestToken
那么不能是字符串。它可能是某种对象,您想要的字符串可能是由该对象的方法或属性返回的。试着console.log(requestToken)
看看那到底是什么。
You also want .slice()
for removing the front of a string.
您还想.slice()
删除字符串的前面。
And you will likely end up with something like:
你可能会得到类似的结果:
myString = requestToken.someProperty.slice(13);
回答by Yusuf X
Coercing it to a string may not solve your problem. console.log(typeof(requestToken)) might give you a clue to what's wrong.
将其强制为字符串可能无法解决您的问题。console.log(typeof(requestToken)) 可能会给你一个错误的线索。
回答by fider
Try to check your object/variable:
尝试检查您的对象/变量:
console.log( JSON.stringify(yourObject) );
or it's type by
或者它的类型
console.log( typeof yourVariable );
回答by Anton Stafeyev
requestToken.toString().slice(13);
or
或者
if(typeof requestToken!="string")
{
requestToken.toString().slice(13);
}else
{
requestToken.slice(13);
}