Tengo una pregunta muy simple. Digamos que tienes esta cadena a y una cadena llamada b que está dentro de a:
var b="anotherthing"; var a="something"+b+"\nsomething"+b;¿Cómo encontrar cada línea que contiene b? Es algo como esto:
var b="anotherthing"; var a="something"+b+"\nsomething"+b; for(var i=a.search(b)-1 ; i<a.lastIndexOf(b,a.length) ; i=a.indexOf(b,i+1)){ ///do something with `i` }¿Cómo se hace para hacer algo como esto ya que el código que se muestra arriba NO funciona?
el concepto de línea es algo que no está definido. si tiene un div con un ancho de 400 px, un texto de prueba tendrá 4 líneas y si tiene un div de 900 px, su texto tendrá 2 líneas.
primero debe definir su línea, como cada 200 caracteres o cada 20 palabras, luego corta su cadena por 200 caracteres y coloca cada uno dentro de una matriz.
entonces tienes que escribir un bucle for para tu matriz de cadenas de líneas. si cada uno contiene su cadena de destino, puede saber y hacer algo con esa línea
Divida el texto en líneas (dividido por \n ) y luego cuente la aparición de cada línea usando expresiones regulares.
const count = (mainString, substring) => (mainString.match(new RegExp(substring, 'g')) || []).length; const statement = `Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.` const needle = 'type' const lines = statement.split('\n') const occurrences = lines.reduce((accumulator, line, lineNumber) => { accumulator[`line ${lineNumber}`] = count(line, needle) return accumulator } , {}) console.log(occurrences) /* { "line 0": 1, "line 1": 0, "line 2": 2, "line 3": 1, "line 4": 0, "line 5": 0, "line 6": 0 } */Suponiendo que cada línea esté separada por \n , podría usar split() para dividir una cadena en sus líneas. Luego, podría usar includes() para cada línea y verificar si esas líneas contienen "something" .
Si desea devolver, por ejemplo, todos los números de línea que contienen "something" , puede usar reduce() . Por supuesto, también podría devolver otras cosas como el número de líneas que contienen una cadena o las propias líneas que contienen la cadena.
const b = "something"; const a =`this is a mulitline string where not ever line contains "something" but some linese do contain "something". The lines that do contain "something" are lines 3, 4 and 6.`; const allLines = a.split("\n"); // contains all lines console.log(allLines); const linesWithSomething = allLines.reduce((linesWithSomething, currentLine, currentLineIndex) => { if(currentLine.includes(b)) linesWithSomething.push(currentLineIndex + 1); return linesWithSomething; }, []) console.log(`Lines with "${b}" are:`, linesWithSomething) .as-console-wrapper { max-height: 100% !important; top: 0; }