我在c#中有一个用来操作字符串的函数,它在C#中使用时运行良好。现在我想将此函数转换为在JavaScript中使用。这是C#中的函数:
public static string TrimString(string str, int lenght)
{
string _str = str;
int _iAdditionalLenght = 0;
for (int i = lenght; i < str.Length; i++)
{
if (_str.Substring(i, 1) == " ")
break;
_iAdditionalLenght++;
}
return str.Substring(0, str.Length < (lenght + _iAdditionalLenght) ? str.Length : (lenght + _iAdditionalLenght));
}
我将其转换为javascript:
function TrimString(str, lengthStr) { //this is my testing 4
var _str = str;
var _iAdditionalLenght = 0;
for (var i = lengthStr; i < str.length; i++) {
if (_str.substring(i, 1) == " ")
break;
_iAdditionalLenght++;
}
return str.substring(0, str.length < (lengthStr + _iAdditionalLenght) ? str.length : (lengthStr + _iAdditionalLenght));
}
但是javascript不起作用。
有谁能告诉我,我怎么能在JavaScript函数中做到这一点?
答案 0 :(得分:1)
子串在C#和&amp;之间有所不同。的JavaScript
例如,strInput =“0123456789”
strInput.SubString(2,3) == will output ==> "234"
strInput.substring(2,3) == will output ==> "2"
instread尝试使用
strInput.substr(2,3) == will output ==> "234"
注意:
substring(Start character position, End Character position)
substr(Start character position, length of Character)
答案 1 :(得分:0)
您需要研究substring
在JavaScript和C#中的工作方式的差异。在C#中,它是应该提取的字符数,在JS中,它是停止提取的索引。