简体   繁体   中英

Select first half of text inside anchor tag using jQuery

Is there a way to target the first half of the text inside an anchor tag using jQuery?

For example, I have these anchor tags.

<a href="">Go to Meeting Center</a> <!-- / target 'Go to' -->
<a href="">Our Departments</a> <!-- / target 'Our' -->

I'd also like to wrap them inside a span tag.

The result should be:

<a href=""><span>Go to</span> Meeting Center</a> <!-- / target 'Go to' -->
<a href=""><span>Our</span> Departments</a> <!-- / target 'Our' -->

It will be applied to all my anchor tags on my website.

You could do this:

var text = $("a").text().split(" ");
var half_of_text = text.splice(0, Math.floor(text.length/2)).join(" ");

The code below loops through all a tags, finds the half text you want (using this answer ) and then creates the span with this half text and puts it in the spans div I created for the spans.

Check this JSFiddle .

HTML

<a href="">Go to Meeting Center</a> <!-- / target 'Go to' -->
<a href="">Our Departments</a> <!-- / target 'Our' -->
<div id="spans"></div>

JavaScript/JQuery

$('a').each(function(i, ele) {
    text = $(this).text().split(" ");
    half_of_text = text.splice(0, Math.floor(text.length/2)).join(" ");

    span = $(document.createElement('span'));
    span.html(half_of_text);
    $('#spans').append(span);
    $('#spans').append(document.createElement('br'));
});

You can try this:

var t = $('a').text();
var middle= '';
for(var i =0; i<Math.floor(t.length/2);i++){
    middle+=t.char(i);
}
console.log(middle);

PS: This has not been tested and is done only to illustrate

 $("a").each(function(){ console.log($(this).text().substr( 0 ,$(this).text().length/2)); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <a href="">Go to Meeting Center</a> <a href="">Our Departments</a> 

"First half" is a very subjective term.

I fear you will have to code this by yourself,
a very basic approach :

 //assuming this is your query string var text = "Go to Meeting Center"; //split string into an array var terms = text.split(" "); //looking for an approximate value the center of the text var half = Math.ceil(terms.length/2); //first "half" of query var selected = terms.splice(0, half).join(" "); console.log(selected); 

You need to decide where is the middle by your own definition, but here is a way to detect the middle with the number of words. You'd get a span around a single word as well with this solution.

You first need to get the text inside the link and use the split function which creates an array from a string according to the separator passed in the argument.

Then, you create a span element containing those words you just replaced and you replace the text inside the link with that span.

 var links = document.querySelectorAll('a'); [].forEach.call(links, function(link_el){ var text_inside = link_el.innerText; var words = text_inside.split(' '); var words_half = Math.ceil(words.length/2); var span_element = document.createElement('span'); var words_string = words.splice(0, words_half).join(' '); link_el.innerText = link_el.innerText.replace(words_string, ''); span_element.innerText = words_string; link_el.prepend(span_element); }); 
 <a href="">Go to Meeting Center</a> <!-- / target 'Go to' --> <a href="">Our Departments</a> <!-- / target 'Our' --> <a href="">Contact</a> <!-- / target 'Contact' --> 

Use the following approach:

 $('a').each(function(i, el){ var parts = $(el).text().split(' '); // splitting anchor text into chunks $(el).html("<span>"+ parts.splice(0, Math.ceil(parts.length/2)).join(" ") +"</span> " + parts.join(" ")); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="">Go to Meeting Center</a> <!-- / target 'Go to' --> <a href="">Our Departments</a> 

Used functions:
JQuery .each()
String.prototype.split() (to split anchor text into chunks)
Array.prototype.splice() (to extract the first half of the text )
Array.prototype.join()

Check this Fiddle

HTML

<a href="">Go to Meeting Center</a> <!-- / target 'Go to' -->
<a href="">Our Departments</a> <!-- / target 'Our' -->

jQuery

$(document).ready(function() {
  $.each($("a"), function(index, element) {
    var text = $(element).text().split(" ");
    text = text.splice(0, Math.floor(text.length/2)).join(" ");

    $(element).html($(element).text().replace(text, "<span>" + text + "</span>"))
  });
});

CSS

a {
  display: block;
}

span {
  color: red !important;
}

NOTE:

If you want to round down use floor , otherwise use ceil .

You can use some of the code provided in other answers to create an easy-to-use approach for applying this to all links site-wide

(see snippet)

 function get_first_half(element) { var text = $(element).text().split(" "); var half_of_text = text.splice(0, Math.floor(text.length / 2)).join(" "); return half_of_text; } function get_back_half(element) { var text = $(element).text().split(" "); var half_of_text = text.slice(Math.floor(text.length / 2), Math.floor(text.length)).join(" "); return half_of_text; } $(document).ready(function() { $("a").each(function(elem) { var first_half = get_first_half(this); var back_half = get_back_half(this); $(this).html("<span>" + first_half + "</span>" + back_half); }); }); 
 span { font-size: 2.0em; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="">Goto Meeting</a> <br> <a href="">Our Departments</a> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM