Javascript 如何确定';这是数字在字符串中的位置
如何确定在带逗号(,)和JS的字符串中,哪个逗号后面是数字13的位置Javascript 如何确定';这是数字在字符串中的位置,javascript,string,numbers,Javascript,String,Numbers,如何确定在带逗号(,)和JS的字符串中,哪个逗号后面是数字13的位置 例如: string-testtest、teststestatestb、testj 字母“s”是第13个字母,在第一个逗号之后。试试看 a.indexOf('s',a.indexOf(',')) 写一个方法 function abc(){ var a = "esttestte,ststestatestbtestj" var c = a.indexOf(',') if (c==-1) alert("'
例如: string-testtest、teststestatestb、testj 字母“s”是第13个字母,在第一个逗号之后。试试看
a.indexOf('s',a.indexOf(','))
写一个方法
function abc(){
var a = "esttestte,ststestatestbtestj"
var c = a.indexOf(',')
if (c==-1)
alert("',' is not present ")
else{
var b =a.indexOf('s',c)
if (b==-1)
alert("'s' is not present after ','")
else
alert("position of 's' after ',' is "+(b+1) )
}
}
您需要使用“,”拆分数组中的字符串,然后使用对应于数组长度的循环检查每个字符串长度。 像
var str=“testtest,teststestatestb,testj”;
var a1=新数组();
a1=str.split(“,”);
对于(变量i=0;i13)
{
//获取单词的第13个索引。
}
}
我不确定我是否理解你的问题。但这里有一个可能的解决方案:
function count_commas_to_position(string,position) {
return string.substring(0,position).replace(/[^,]/g,'').length
}
// if you don't want to count commas on `position`
function count_commas_to_position(string,position) {
return string.substring(0,position-1).replace(/[^,]/g,'').length
}
var string = "testtest,teststestatestb,testj"
var comma_count = count_commas_to_position(string,13);
是的,但是第13个字母没有定义。我必须先找到第13个字母。如果我写9,这是第一个逗号,它返回1,但对我来说,它必须是0。我不想“数”逗号,但我可以忽略这一点。非常感谢你!我已经更新了函数,因此它不计算
位置上的逗号
function count_commas_to_position(string,position) {
return string.substring(0,position).replace(/[^,]/g,'').length
}
// if you don't want to count commas on `position`
function count_commas_to_position(string,position) {
return string.substring(0,position-1).replace(/[^,]/g,'').length
}
var string = "testtest,teststestatestb,testj"
var comma_count = count_commas_to_position(string,13);