I'm trying to be able to select the first and last instances of a given character(s) within a span element.
e.g.
<span class="foo">hello (this is hello)</span>
I want to be able to find the first bracket and the last bracket within this span and append a class them so the output might be:
<span class="foo">hello <span class="bar">(this is hello)</span></span>
Is this possible? I've looked at first in jQuery but it seems to only work for selecting elements rather than characters.
2 Answers 2
You can use a regex :
$('.foo').html(function(_, html){
return html.replace(/\((.*)\)/, '<span class="bar">(1ドル)</span>')
});
Demonstration (click "Run with JS)
If you want to deal with more than one bracked group, use
$('.foo').html(function(_, html){
return html.replace(/\(([^\)]*)\)/g, '<span class="bar">(1ドル)</span>')
});
2 Comments
function(_, html){ you used?_ is just a variable name, I could have used html(function(i, html) but I like to use _ for unused variables.Javascript provides native methods for this. Strings have an indexOf() method that returns the location of the first instance of a given string or character and a lastIndexOf() method that returns the last instance. E.g.:
var firstE = "Hello, Ben!".indexOf('e'); // firstE = 1
var lastE = "Hello, Ben!".lastIndexOf('e'); //lastE = 8