Reputation: 787
Are there any string replace methods that will replace anything between 2 positions, i.e. range.
When a user highlights a string of text in a textarea I'm able to get the start and end position. I now want to replace that text that's highlighted.
Upvotes: 0
Views: 2204
Reputation: 129792
You can use substrings:
var newString =
originalString.substring(0, startIndex) +
myReplacementString +
originalString.substring(endIndex);
You could also use regex:
var rx = new RegExp('^([\\s\\S]{' + startIndex + '})[\\s\\S]{' + (endIndex - startIndex) + '}([\\s\\S]*)$');
var newString = originalString.replace(rx, '$1' + myReplacementString + '$2');
... but I would prefer substrings, in this scenario.
Upvotes: 2