JavaScript find and replace a character in between specified characters

Pugazh :

I'm trying to replace all [space] with - between __tt and tt__

I could replace space in the entire string with below regex.

var str = document.getElementById('tt').value;
str = str.replace(/(?<=__tt.*) (?=.*tt__)/g, '-');
console.log(str);
textarea {
  width: 400px;
  min-height: 100px;
}
<textarea id="tt">This is a long text __tt where i want 
to replace
some text tt__ between some character
</textarea>

Is there a way I could do the replace only between __tt and tt__ tag ???

The fourth bird :

Without lookarounds, which are not yet fully supported by all browsers you might also use a replacement using a callback function over the selected match only.

str = str.replace(/__tt.*?tt__/g, m => m.replace(/ /g, "-"));

var str = 'This is a long text __tt where i want to replace some text tt__ between some character';
str = str.replace(/__tt.*?tt__/g, m => m.replace(/ /g, "-"));
console.log(str);

Note

If you want a single hyphen in the replacement for multiple consecutive spaces, you could repeat the space 1 or more times using + or match 1 or more whitespace chars using \s+

With the updated question, get the text of the element:

var elm = document.getElementById("tt");
elm.textContent = elm.textContent.replace(/__tt[^]*?tt__/g, m => m.replace(/ +/g, "-"));
<textarea id="tt" rows="4" cols="50">This is a long text __tt where i want
to replace
some text tt__ between some character
</textarea>

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=383054&siteId=1