0

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.

asked May 5, 2013 at 18:40

2 Answers 2

1

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>')
});
answered May 5, 2013 at 18:42
Sign up to request clarification or add additional context in comments.

2 Comments

Can you provide documentation for that function(_, html){ you used?
It's this one from jQuery. _ is just a variable name, I could have used html(function(i, html) but I like to use _ for unused variables.
0

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
answered May 5, 2013 at 18:52

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.