Replace all pattern instances with regular expressions in Javascript / jQuery

Firstly, I know little about regular expression and you need to buy a book because it seemed to me that it was difficult to pick me up.

Ultimately, I want to take the dom element and replace the text in brackets "[" and "]" and insert a link around the text, and there can be several sets of brackets in the line.

function changeTip() { var link = '<a href="' + $('#txtURL').attr('value') + '" target="_blank">'; $('.tipoftheweektip').html($('#txtTip').attr("value").replace('[', link).replace(']', '</a>')); } 

This works, with the exception of:

  • does not work in the second set of brackets
  • If there is no closing brace, it deletes all text before opening the brace

I reviewed the examples and because the regular expressions code uses straight brackets, I cannot figure out how to search for a bracket and replace it.

Anyone who has done something like this that they can share? Thanks in advance.

+4
source share
2 answers
 .replace(/\[([^\]]*)\]/g, link + "$1</a>") 

which means finding the text between [and] and replacing it with the value of the link, the text itself and ''. This ensures that the square brackets match. "G" means "do this several times (globally)."

+11
source

This will go through the entire line and replace it with your chosen word or phrase with another. (the view is complex, but it works and is very reusable)

var string = "this is some test text. You can replace all instances with any word / phrase in 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
source

Source: https://habr.com/ru/post/1286721/


All Articles