搜索术语,将其包装到<span>标记中

时间:2016-02-19 21:21:30

标签: javascript jquery

我有一些文本存储在变量$target中:

var $target = jQuery(this).text();

文字可以是:

Hello world, attack on titan 進撃の巨人 is amazing!

然后我通过以下变量$term

var $term = jQuery(this).prev().text();

它可以包含类似的内容:

attack on titan

在名为$result的新变量中,我想在$target中搜索$term的内容并将其包装到<span>标记中。因此,在此示例中,$result将为:

var $result = 'Hello world, <span>attack on titan</span> 進撃の巨人 is amazing!';

一个相对简单的请求,但我的目标是在这里表现。什么是最好的方法?

3 个答案:

答案 0 :(得分:3)

<强> Working Fiddle

以下是一种相对简单的方法:

var $target = "Hello world, attack on titan 進撃の巨人 is amazing!";
var $term = "attack on titan";
var $result;

$result = $target.replace($term, "<span>"+$term+"</span>");

console.log($result); // => Hello world, <span>attack on titan</span> 進撃の巨人 is amazing!

我们所做的就是将term中的target替换为term,并<span></span>包裹var wrapInSpan = function(target, term){ return target.replace(term, "<span>"+term+"</span>"); } $result = wrapInSpan($target, $term); console.log($result); // => Hello world, <span>attack on titan</span> 進撃の巨人 is amazing!

此外,如果您计划不止一次这样做,我建议您简化流程并使其成为一个功能:

String

注意:

它通常被称为bad practice to altar the prototype of a native object,就像在@ Michael的解决方案中一样。如果您想使解决方案更加模块化,我建议将其添加到自己的独立功能中,就像在我的解决方案中一样,而不是篡改'use strict' // Google Maps API and Places library functions to start the map var map; var service; var infowindow; function initialize() { var coimbra = new google.maps.LatLng(40.209658,-8.419721); map = new google.maps.Map(document.getElementById('map'), { center: coimbra, zoom: 18, disableDefaultUI: true }); // Request for places library for nearby places of interest // Most of the code comes from the google Maps API documentation var request = { location: coimbra, radius: '400', types: ['store', 'café','food', 'bar'] }; service = new google.maps.places.PlacesService(map); service.nearbySearch(request, callback); } function callback(results, status) { if (status == google.maps.places.PlacesServiceStatus.OK) { for (var i = 0; i < results.length; i++) { var place = results[i]; createMarker(results[i]); } } } // Function that receives the results of the callback function and adds the markers to the map function createMarker(place) { var placeLoc = place.geometry.location; var marker = new google.maps.Marker({ map: map, position: place.geometry.location }); }对象。

答案 1 :(得分:0)

var target="Hello world, attack on titan 進撃の巨人 is amazing!";
var term="attack on titan";

var result=target.replace(term,"<span>"+term+"</span>");

答案 2 :(得分:0)

您可以尝试使用.indexOf方法在$ target中搜索$ term。

var $target = "this is some cool text";
var $term = "cool";
var $result;
if($target.indexOf($term) != -1) {
    $result = $target.replace($term, "<span>"+$term+"</span>");
}

else {
alert('Not there')
}