Javascript 如何在多行字符串中查找字符位置(行、列)?

Javascript 如何在多行字符串中查找字符位置(行、列)?,javascript,string,algorithm,Javascript,String,Algorithm,如何在多行字符串中找到当前字符的位置? 如果字符串中的每一行长度相同,那么就很容易了。例如 const str=`hello 你好 你好` 常量findPos=(str,ind)=>{ 常量[cols]=str.split('\n'); 返回{row:ind/cols.length | 0,col:ind%cols.length}; }; findPos(str,12)/{row:2,col:2} 但是,如果每一行的长度不同,我该怎么做呢?例如 const str=`hello 从…起 我的

如何在多行字符串中找到当前字符的位置? 如果字符串中的每一行长度相同,那么就很容易了。例如

const str=`hello
你好
你好`
常量findPos=(str,ind)=>{
常量[cols]=str.split('\n');
返回{row:ind/cols.length | 0,col:ind%cols.length};
};
findPos(str,12)/{row:2,col:2}
但是,如果每一行的长度不同,我该怎么做呢?例如

const str=`hello
从…起
我的
古老的
朋友`
findPos(str,12)/{row:3,col:1}

使用while循环在拆分行上迭代,从要执行的字符数中减去当前行的长度。如果长度小于要转到的字符数,则将要转到的字符作为
列返回,并将迭代的行数作为
行返回:

constfindpos=(输入,indextofId)=>{
常量行=input.split('\n');
设charsToGo=indexToFind;
设lineIndex=0;
while(lineIndexconsole.log(findPos(str,12));//{row:3,col:1}
当您需要查找每个字符位置的数组时

您不需要创建函数来逐个查找位置

此外,在创建对象时,可以保留占位符和字符,以便快速搜索

const str=`hello
从…起
我的
古老的
朋友`
函数createPos(str){
let out=str.split('\n').map(e=>[…e]);
设place=1;
return out.map((arr,row)=>arr.map((char,col)=>({char,row,col,place:place++})).flat();
}
函数findPos(str,n){
返回createPos(str).find(e=>e.place==n)
}
log('all chars\n',createPos(str));

console.log('found char\n',findPos(str,12))
您要查找哪个字符?@brk字符串中的每个字符,完整的结果将是位置对象数组[{row:number,col:number},{row:number,col:number},{row:number,col:number},{row:number,col number}…等等]我如何改进它以考虑换行字符?