Reputation: 9561
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 ???
Upvotes: 1
Views: 79
Reputation: 163362
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>
Upvotes: 2
Reputation: 161
can try it
let str = 'This is a long text __tt where i want to replace some text tt__ between some character';
str = str.replace(/__tt.*?tt__/g, (item) => item.replace(/ /g, "-"));
console.log(str);
Upvotes: 1
Reputation: 386604
You could take positive look behind and look ahead.
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, '-');
console.log(str);
Upvotes: 3