/    Sign up×
Community /Pin to ProfileBookmark

finding position in a string

I’m swapping selected text in a textarea to replace it with something else.
Got it working using replace() but the problem is it replaces the first position of the selected in the string rather than the actual position.
ie. if the string has two of the same words in it and I wanted to replace the second one, it replaces the first.

[CODE]
function makelink(txtarea) {
var sl = (txtarea.value).substring(txtarea.selectionStart,txtarea.selectionEnd);
if (sl==”) {
alert(‘First Select Some Text!’);
return false;
}
var url = prompt (“Enter URL:”,””);
var link = “<a href=””+url+””>”+sl+”</a>”;
var tx = txtarea.value;
tx=tx.replace(sl, link);
txtarea.value = tx;
}[/CODE]

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@so_is_thisDec 21.2006 — [CODE]
function makelink(txtarea) {
var sl = (txtarea.value).substring(txtarea.selectionStart,txtarea.selectionEnd);
if (sl=='') {
alert('First Select Some Text!');
return false;
}
var url = prompt ("Enter URL:","");
var link = "<a href=""+url+"">"+sl+"</a>";
txtarea.value = txtarea.substring(0,txtarea.selectionStart) + link + txtarea.substr(txtarea.selectionEnd + 1);
}[/CODE]
Copy linkTweet thisAlerts:
@rohiauthorDec 21.2006 — thank you.

got it sussed now, but for some reason had to make variables(objects?)
[CODE]function makelink(txtarea) {
var sl = (txtarea.value).substring(txtarea.selectionStart,txtarea.selectionEnd);
if (sl=='') {
alert('First Select Some Text!');
return false;
}
var url = prompt ("Enter URL:","");
var link = '<a href="' + url + '">' + sl + '</a>';
var selStart = txtarea.selectionStart;
var selEnd = txtarea.selectionEnd;
var tx = txtarea.value
var stx = tx.substring(0,selStart) + link + tx.substr(selEnd);
txtarea.value = stx
}[/CODE]
Copy linkTweet thisAlerts:
@so_is_thisDec 21.2006 — Oops, this:

txtarea.value = txtarea.substring(0,txtarea.selectionStart) + link + txtarea.substr(txtarea.selectionEnd + 1);

should have been this:

txtarea.value = txtarea.[COLOR=Red]value.[/COLOR]substring(0,txtarea.selectionStart) + link + txtarea.[COLOR=Red]value.[/COLOR]substr(txtarea.selectionEnd + 1);
×

Success!

Help @rohi spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.16,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...