admin管理员组

文章数量:1397102

Imagine I have the following multi-line Javascript string:

school

apple

~carrot

dog

I want to take any line that starts with "~" and replace it with "#(contents of line)#". So in this example I want to find "~carrot" and replace it with "#carrot#".

I'm trying to e up with a solution using regular expressions but can't figure out a way to replace some matched string with a modified version of itself (with the prepended/appended characters.)

Any help would be appreciated, hoping one example will turn on the lightbulb...

Imagine I have the following multi-line Javascript string:

school

apple

~carrot

dog

I want to take any line that starts with "~" and replace it with "#(contents of line)#". So in this example I want to find "~carrot" and replace it with "#carrot#".

I'm trying to e up with a solution using regular expressions but can't figure out a way to replace some matched string with a modified version of itself (with the prepended/appended characters.)

Any help would be appreciated, hoping one example will turn on the lightbulb...

Share Improve this question edited Aug 21, 2012 at 14:35 ARW asked Aug 21, 2012 at 14:22 ARWARW 3,4167 gold badges34 silver badges43 bronze badges 4
  • 2 Is "carrot" a constant string that can be hardcoded or the contents of a variable? – Mark Byers Commented Aug 21, 2012 at 14:24
  • And what exactly do you want to mach? Lines starting with ~? You have to provide some more information. What makes ~carrot so special that you want to replace it? – Felix Kling Commented Aug 21, 2012 at 14:25
  • Sorry, yes carrot is a variable and yes I want to replace any lines that start with "~" with "#(contents of line)#". Thanks! – ARW Commented Aug 21, 2012 at 14:33
  • Carrot is just an example, I would not know what it actually was in advance. – ARW Commented Aug 21, 2012 at 14:34
Add a ment  | 

2 Answers 2

Reset to default 9

thestring.replace(/~(\w+)/g, "#$1#");

The parentheses "capture" the word (\w+) and the $1 in the result references what's captured.

It's really easy. Suppose you have your string in OldString

var OldString = "school apple  ~carrot dog";

var myNewString = OldString.replace(/~carrot/, "#carrot#");

document.write("Old string =  " + OldString); 
document.write("<br />New string = " + myNewString);

Hope it helps

本文标签: regexFind substring in Javascript and prependappend some charactersStack Overflow