programing

jQuery 문자열 찾기 및 바꾸기

minimums 2023. 10. 15. 17:11
반응형

jQuery 문자열 찾기 및 바꾸기

웹사이트 어딘가에 특정 텍스트가 있는데, "롤리팝"이라고 합시다. 그리고 이 문자열이 발생하는 모든 것을 "mashmellow"로 대체하고 싶습니다.문제는 텍스트가 정확히 어디에 있는지 모른다는 것입니다.제가 할 수 있는 일은 다음과 같습니다.

$(body).html($(body).html().replace('lollypops', 'marshmellows'));

이것은 아마 효과가 있겠지만, HTML을 가능한 한 적게 다시 써야 해서, 다음과 같은 생각을 하고 있습니다.

  1. 문자열 검색
  2. 가장 가까운 부모 요소 찾기
  3. 가장 가까운 상위 요소만 다시 쓰기
  4. 전부는 아니지만 특성에서도 이를 바꿉니다. 예를 들어 에 바꿉니다.class, 안에 없는src

예를 들어, 저는 이런 구조를 가지고 있을 것입니다.

<body>
    <div>
        <div>
            <p>
               <h1>
                 <a>lollypops</a>
               </h1>
            </p>
            <span>lollypops</span>
        </div>
    </div>
    <p>
       <span class="lollypops">Hello, World!</span>
       <img src="/lollypops.jpg" alt="Cool image" />
    </p>
<body>

이 예에서는 "롤리팝"이 발생할 때마다 교체됩니다.<img src="...동일하게 유지될 것이고 실제로 조작될 수 있는 유일한 요소는<a>둘다<span>s.
이거 할 줄 아는 사람?

당신은 다음과 같은 것을 할 수 있습니다.

$("span, p").each(function() {
    var text = $(this).text();
    text = text.replace("lollypops", "marshmellows");
    $(this).text(text);
});

검사가 필요한 모든 태그를 적합한 클래스 이름으로 텍스트로 표시하는 것이 좋습니다.

또한 성능 문제가 있을 수 있습니다.jQuery나 javascript는 일반적으로 이런 종류의 작업에는 적합하지 않습니다.서버 쪽에서 하는 게 낫습니다.

이런 식으로 할 수 있습니다.

$(document.body).find('*').each(function() {
    if($(this).hasClass('lollypops')){ //class replacing..many ways to do this :)
        $(this).removeClass('lollypops');
        $(this).addClass('marshmellows');
    }
    var tmp = $(this).children().remove(); //removing and saving children to a tmp obj
    var text = $(this).text(); //getting just current node text
    text = text.replace(/lollypops/g, "marshmellows"); //replacing every lollypops occurence with marshmellows
    $(this).text(text); //setting text
    $(this).append(tmp); //re-append 'foundlings'
});

예: http://jsfiddle.net/steweb/MhQZD/

당신은 다음과 같은 것을 할 수 있습니다.

HTML

<div class="element">
   <span>Hi, I am Murtaza</span>
</div>


jQuery

$(".element span").text(function(index, text) { 
    return text.replace('am', 'am not'); 
});

아래는 제가 일부 텍스트를 컬러 텍스트로 대체하기 위해 사용한 코드입니다.간단해요, 텍스트를 가져가서 한번의 시간 안에 대체해요.HTML태그. 해당 클래스 태그의 각 단어에 대해 작동합니다.

$('.hightlight').each(function(){
    //highlight_words('going', this);
    var high = 'going';
    high = high.replace(/\W/g, '');
    var str = high.split(" ");
    var text = $(this).text();
    text = text.replace(str, "<span style='color: blue'>"+str+"</span>");
    $(this).html(text);
});
var string ='my string'
var new_string = string.replace('string','new string');
alert(string);
alert(new_string);

문자열 컨테이너에 클래스를 추가하고 내부 텍스트를 교체하지 않는 이유는 무엇입니까?이 예처럼 말입니다.

HTML:

<div>
    <div>
        <p>
           <h1>
             <a class="swapText">lollipops</a>
           </h1>
        </p>
        <span class="swapText">lollipops</span>
    </div>
</div>
<p>
   <span class="lollipops">Hello, World!</span>
   <img src="/lollipops.jpg" alt="Cool image" />
</p>

jQuery:

$(document).ready(function() {
    $('.swapText').text("marshmallows");
});

언급URL : https://stackoverflow.com/questions/5115152/jquery-find-and-replace-string

반응형