How to wrap each word of an element in a span tag?

前端 未结 8 1790
忘掉有多难
忘掉有多难 2020-12-01 07:05
$(\"div.date\")
    .contents()
    .filter(
        function(){
            return this.nodeType != 1; 
        })
    .wrap(\"\");

I

8条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-01 07:32

    You don't need jQuery for this simple task. String.prototype.replace and regex should do the trick.

    I just made some simple utility functions, that wraps letters, words and lines:

    /**
     * Wraps a string around each character/letter
     *
     * @param {string} str The string to transform
     * @param {string} tmpl Template that gets interpolated
     * @returns {string} The given input as splitted by chars/letters
     */
    function wrapChars(str, tmpl) {
      return str.replace(/\w/g, tmpl || "$&");
    }
    
    /**
     * Wraps a string around each word
     *
     * @param {string} str The string to transform
     * @param {string} tmpl Template that gets interpolated
     * @returns {string} The given input splitted by words
     */
    function wrapWords(str, tmpl) {
      return str.replace(/\w+/g, tmpl || "$&");
    }
    
    /**
     * Wraps a string around each line
     *
     * @param {string} str The string to transform
     * @param {string} tmpl Template that gets interpolated
     * @returns {string} The given input splitted by lines
     */
    function wrapLines(str, tmpl) {
      return str.replace(/.+$/gm, tmpl || "$&");
    }
    

    The usage is pretty simple. Just pass in the string to wrap as first argument. If you need custom markup, pass it in as the second argument, while $& is replaced by each char/word/line.

    var str = "Foo isn't equal\nto bar.";
    wrapChars(str); // => "Foo isn't equal to bar."
    wrapWords(str); // => "Foo isn't equal to bar."
    wrapLines(str); // => "Foo isn't equal to bar."
    

提交回复
热议问题