Replace all instances of a pattern with regular expressions in Javascript / jQuery

前端 未结 2 1691
执笔经年
执笔经年 2021-01-20 00:33

First off I don\'t know much about regex and need to buy a book because it\'s has proven to me to be difficult to pickup.

Ultimately I want to take a dom element, an

相关标签:
2条回答
  • 2021-01-20 00:50
    .replace(/\[([^\]]*)\]/g, link + "$1</a>")
    

    which means, find text between [ and ] and replace it with the value of link, the text itself and ''. This ensures matching square brackets. The 'g' means 'do it multiple times (globally)'.

    0 讨论(0)
  • 2021-01-20 01:02

    This will loop through an entire string and replace it with your chosen word or phrase with another. (kind of complicated but it works and is very reusable)

    var string = "this is some test text. You can replace all instances of any word/phrase within this text"

    var new string = string.findAndReplace("text", "BOO!");

    Object.prototype.findAndReplace = function( searchText, replace ) {
        var matchCount = 0;
            var text = this;
    
            for( var i = 0; i<text.length; i++ ) {
                var textSearched = "";
    
                for(var x = 0; x<searchText.length; x++) {
                    var currentText = text[i+x];
    
                    if( currentText != undefined ) {
                        textSearched += currentText;
                    }
                }
    
                if( textSearched == searchText ) {
                    matchCount++;
                }
    
                console.log( textSearched );
            }
    
            for(var i=0; i<matchCount; i++) {
                text = text.replace( searchText, replace );
            }
    
            return text;
        }
    
    0 讨论(0)
提交回复
热议问题