remove first match from string in javascript and jquery
I have string like this 'set , many, like, see, what'
when i create this string i also create div
with linked element
<div>
<a href="#">set</a>
开发者_开发知识库<a href="#">many</a>
<a href="#">like</a>
...
</div>
and also create hidden input with 'set , many, like, see, what'
value ... when we click on linked element we have string of link ( example: set
)
how remove first match of string and strip it from hidden input?
ps: i said first match because one element can repeat
Where link
is a reference to one of the links, theString
is a reference to your string, and hidden
is a reference to your hidden input control, you can do something like this:
link.onclick = function(e)
{
var expr = new RegExp("\b" + this.innerHTML + "\b(, ?)?");
theString = theString.replace(expr, "");
hidden.value = theString;
}
var anchors = document.getElementById('container').getElementsByTagName('a'),
hiddenInput = document.getElementById('hidden');
for (var i = 0, anchorsLength = anchors.length; i < anchorsLength; i++) {
var anchor = anchors[i];
anchor.onclick = function() {
var term = anchor.innerHTML;
hiddenInput.value = hiddenInput
.value
.replace(new RegExp(term + ',\s?'), '');
}
}
This code allows you to click one of those anchors, in which it will remove the first occurrence of the anchor's text node, and the ,
and any optional whitespace character.
精彩评论