Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I replace multiple items in a string?

Starting string:

I like [dogs], [cats], and [birds]

Final output needed:

I like <a href="#">dogs</a>, <a href="#">cats</a>, and <a href="#">birds</a>

So basically changing items with brackets to links.

like image 916
Shpigford Avatar asked Feb 08 '11 18:02

Shpigford


People also ask

How do you replace multiple values?

Find and replace multiple values with nested SUBSTITUTE The easiest way to find and replace multiple entries in Excel is by using the SUBSTITUTE function. The formula's logic is very simple: you write a few individual functions to replace an old value with a new one.

How do you replace all elements in a string?

To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag. replaceAll() method is more straight forward.

How do you replace multiple values in a string in Python?

01) Using replace() method Python offers replace() method to deal with replacing characters (single or multiple) in a string. The replace method returns a new object (string) replacing specified fields (characters) with new values.

How do I replace multiple characters in a string in SQL?

Using the REPLACE() function will allow you to change a single character or multiple values within a string, whether working to SELECT or UPDATE data.


2 Answers

Use this expression:

var str = 'I like [dogs], [cats], and [birds]';
alert(str.replace(/\[(.+?)\]/g, '<a href="#">$1</a>'));
  • \[(.+?)\] asks for a literal [, to lazily match and capture anything, then to match a literal ]. Replace with the captured stuff enclosed in <a> tags.

  • The g modifier means global replacement, i.e. find and replace every match and not just the first.

jsFiddle preview

like image 179
BoltClock Avatar answered Oct 14 '22 08:10

BoltClock


It's a simple string replace.

function tagIt(source)
{
  return source.replace('[', '<a href="#">').replace(']', '</a>');
}
like image 44
GolezTrol Avatar answered Oct 14 '22 07:10

GolezTrol