AnApprentice
AnApprentice

Reputation: 110950

How to find and replace a string in a block of text?

Given a block of string like:

var copy = "Hello world what is the day @James Bond blah bah blah blah...";

Using jQuery/JS, given:

var term = "James Bond";
var id = "XXXXXX";

How can I find all matches with '@' + term and return the something like this:

"Hello world what is the day @[XXXXXX:James Bond] blah bah blah blah..."

Thanks

Upvotes: 2

Views: 762

Answers (2)

gustavotkg
gustavotkg

Reputation: 4399

Just use replace function:

var term = "James Bond", id = "XXXXXXX";
"Hello world what is the day @James Bond blah bah blah blah...".replace("@"+term, "@["+id+":"+term+"]");

Upvotes: 5

Veldmuis
Veldmuis

Reputation: 4838

var toReplace = "@" + term
var replaceWith = "@[" + id + ":" + term + "]"

From there you should be able to use a normal string replacing function.

Upvotes: 1

Related Questions