Solution
/\b(?!especifica\b)(\w+\b)(\s+)\b(?!especifica\b)/gi
Description
The regular expression consumes the word before space (and the capture in the first group), and then captures the blanks within group 2 ( grupo[2]
).
/
\b # límite de palabra completa (antes de la 1er palabra)
(?!especifica\b) # aserción (negative lookahead) para ver que no sea "especifica"
(\w+\b) # consume la primer palabra
(\s+) # coincide con los espacios en blanco buscados
\b # límite de palabra completa (antes de la 2da palabra)
(?!especifica\b) # aserción para ver que la 2da palabra no sea "especifica"
/gi # g: todas las coincidencias; i: no importa mayúsculas/minúsculas
Next, we'll use the starting position from where the match started, and the length of the first word ( grupo[1]
) to determine where the blank starts.
Code
var regex = /\b(?!especifica\b)(\w+\b)(\s+)\b(?!especifica\b)/gi;
var texto = 'especifica especifica
tres especifica
especifica cuatro
cinco seis';
var grupo, posInicial, posFinal, resultado = "";
while ((grupo = regex.exec(texto)) !== null) {
posInicial = grupo.index + grupo[1].length;
posFinal = regex.lastIndex;
resultado = resultado + "\n"
+ 'Se encontró "' + grupo[2]
+ '" desde la posición ' + posInicial
+ ' hasta la posición ' + posFinal
+ ' (después de la palabra "' + grupo[1] + '")';
}
document.getElementById("resultado").innerText = resultado;
<pre id="resultado"></pre>
Generate the regex dynamically
If you want to generate the regular expression dynamically, you have to make sure to escape any metacharacter that may be inside the specific word.
function generarExpresion(especifica) {
especifica = especifica.replace(/[\/\^$*+?.()|[\]{}]/g, '\$&');
return new RegExp("\b(?!" + especifica + "\b)(\w+\b)(\s+)\b(?!" + especifica + "\b)", "gi");
}
var regex = generarExpresion("especifica");
Remove (replace) blank spaces
Using replace, we can remove all blanks, except those that surround a specific word. For that, all matches (the first word and the space) are replaced by the value of the first group $1
(only the first word):
function juntarTodo() {
var regex = /\b(?!especifica\b)(\w+\b)(\s+)\b(?!especifica\b)/gi;
var texto = document.getElementById("area").value;
var resultado = texto.replace(regex, "$1");
document.getElementById("resultado").value = resultado;
}
<textarea id='area' rows="4" cols="60">especifica especifica uno especifica dos
tres especifica cuatro cinco seis</textarea>
<button id='boton' onclick="juntarTodo()">Juntar Todo</button>
<textarea id='resultado' rows="4" cols="60"></textarea>
Demo in regex101