• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EDT 09:14
CEST 15:14
KST 22:14
  • Home
  • Forum
  • Calendar
  • Streams
  • Liquipedia
  • Features
  • Store
  • EPT
  • TL+
  • StarCraft 2
  • Brood War
  • Smash
  • Heroes
  • Counter-Strike
  • Overwatch
  • Liquibet
  • Fantasy StarCraft
  • TLPD
  • StarCraft 2
  • Brood War
  • Blogs
Forum Sidebar
Events/Features
News
Featured News
Team Liquid Map Contest #22: Results and Winners7Code S Season 2 (2026): RO4 and Finals Preview12TL.net Map Contest #22 - Voting & Ladder Map Selection7Code S Season 2 (2026) - RO8 Preview5[ASL21] Finals Preview: Two Legacies21
Community News
Douyu Cup 2026: $20,000 Legends Event (June 26-28)9[BSL22] Non-Korean Championship from 13 to 28 June4Weekly Cups (May 25-31): Clem doubles, 2v2 circuit heads toward finale0StarCraft II 5.0.16 PTR Patch Notes may 26th156Weekly Cups (May 18-24): MaxPax wins doubles0
StarCraft 2
General
RSL S6 finale at Blizzcon TL Poll: How do you feel about the 5.0.16 PTR balance changes? Oliveira Would Have Returned If EWC Continued Team Liquid Map Contest #22: Results and Winners High level ptr replays? where can I find them?
Tourneys
Douyu Cup 2026: $20,000 Legends Event (June 26-28) Maestros of The Game 2 announcement and schedule ! Sparkling Tuna Cup - Weekly Open Tournament Sea Duckling Open (Global, Bronze-Diamond) GSL Code S Season 2 (2026)
Strategy
[G] Having the right mentality to improve
Custom Maps
[D]RTS in all its shapes and glory <3
External Content
Mutation # 530 One For All The PondCast: SC2 News & Results Mutation # 529 Opportunities Unleashed Mutation # 528 Infection Detected
Brood War
General
Where is EffOrt? BGH Auto Balance -> http://bghmmr.eu/ BW General Discussion vespene.gg — BW replays in browser Quality of life changes in BW that you will like ?
Tourneys
[Megathread] Daily Proleagues [ASL21] Grand Finals [BSL22] Grand Finals - Sunday 21:00 CEST Escore Tournament StarCraft Season 2
Strategy
Creating a full chart of Zerg builds Relatively freeroll strategies Why doesn't anyone use restoration? Any training maps people recommend?
Other Games
General Games
Stormgate/Frost Giant Megathread Path of Exile Nintendo Switch Thread PC Games Sales Thread ZeroSpace Megathread
Dota 2
Looking for a Dota Mentor Official 'what is Dota anymore' discussion
League of Legends
Heroes of the Storm
Simple Questions, Simple Answers Heroes of the Storm 2.0
Hearthstone
Deck construction bug Heroes of StarCraft mini-set
TL Mafia
Vanilla Mini Mafia
Community
General
US Politics Mega-thread Russo-Ukrainian War Thread UK Politics Mega-thread Canadian Politics Mega-thread Trading/Investing Thread
Fan Clubs
The HerO Fan Club! The herO Fan Club!
Media & Entertainment
Movie Discussion! [Req][Books] Good Fantasy/SciFi books [TV/BOOK] *SPOILERS* Game of Thrones Discussion [Manga] One Piece
Sports
TeamLiquid Health and Fitness Initiative For 2023 2024 - 2026 Football Thread Formula 1 Discussion Cricket [SPORT] NBA General Discussion
World Cup 2022
Tech Support
Computer Build, Upgrade & Buying Resource Thread Facing Challenges in Mobile App Development
TL Community
The Automated Ban List
Blogs
Does Workplace Frustration D…
TrAiDoS
An Exploration of th…
waywardstrategy
I'm an arrogant trash talke…
FlaShFTW
Gauntlet SC2: A Retrospectiv…
Ctone23
Why RTS gamers make better f…
gosubay
Customize Sidebar...

Website Feedback

Closed Threads



Active: 9652 users

[H] javascript regex replacing

Blogs > evanthebouncy!
Post a Reply
evanthebouncy!
Profile Blog Joined June 2006
United States12796 Posts
September 08 2010 13:10 GMT
#1
I have a good, working regex.
I have a function which takes a string, and process it a little and return a desirable new string.

I have a huge string which has multiple locations where my regex would match it.

What I want to do is:
Take my regex, somehow find all occurrences of substring that matches my regex, process and replace those substring with the function i described above.

Trouble:
One would try to do
string.replace(regix, newString); as a natural thing, but it doesn't quite work because the newString depends on whatever my regix has captured.

Then the next thing one would try would be
string.replace(regix, some regex containing $1)
Here $1 is whatever my regix has captured, assume I captured it with ( ). However, the new string cannot be expressed nicely as a regex, and I'd have to use the function for further process.

What I really really wanted is to somehow say this:
string.replace(regix, f($1))
That would be ideal, however $1 is not really a string object and I have failed to cast it as one...

What do I do? T__T

Life is run, it is dance, it is fast, passionate and BAM!, you dance and sing and booze while you can for now is the time and time is mine. Smile and laugh when still can for now is the time and soon you die!
Osmoses
Profile Blog Joined October 2008
Sweden5302 Posts
Last Edited: 2010-09-08 13:48:34
September 08 2010 13:23 GMT
#2
If I understand you correctly, I think you need to add a g at the end of your regexp (like /[0-9]/g) to make it global, as without it the regexp will only handle the first occurance.

Edit: nm now I see what you're saying. I think your best bet is to run the string several times with different regexps if you need different replacements for each kind.

... Or you could run the regexp in a search without the global tag, take the return data and process it, which would be the first occurance, and then you can run the regexp (not global) replace once with the result. Loop.

Think that would work?

edit2: seems search just returns the position where the match occured. Simple version, use two strings, one to retrieve results from and one to insert them into.
Excuse me hun, but what is your name? Vivian? I woke up next to you naked and, uh, did we, um?
evanthebouncy!
Profile Blog Joined June 2006
United States12796 Posts
September 08 2010 13:35 GMT
#3
On September 08 2010 22:23 Osmoses wrote:
If I understand you correctly, I think you need to add a g at the end of your regexp (like /[0-9]/g) to make it global, as without it the regexp will only handle the first occurance.


my regex has /g in it.
Life is run, it is dance, it is fast, passionate and BAM!, you dance and sing and booze while you can for now is the time and time is mine. Smile and laugh when still can for now is the time and soon you die!
Adeny
Profile Blog Joined January 2009
Norway1233 Posts
Last Edited: 2010-09-08 13:54:43
September 08 2010 13:53 GMT
#4
Warning: I don't know javascript
So you want to replace the actual occurences in the bigger string? Some pseudo-code would help but I'm guessing this is what you want to do:

note: pseudo for the sake of having an example

string a = "hello world!"
string b = (regex, a) to get "hello"
if (b == "hello")
string.replace(a.b, "hi");

string a should now = "hi world!"


I think I would try to store the location of the regex match, for example if the match starts at bigString[50] and is 10 characters long, create a new bigString2, make bigString2[0..49] = bigString[0..49], then sub in the new string from the regex'd string.
Again, I have no idea what kind of shennanigans you can do to your javascript strings so I someone is probably going to stroll on in and do it in one line.
Konni
Profile Blog Joined February 2003
Germany3044 Posts
September 08 2010 13:55 GMT
#5
What is $1 and where do you get it from?
igotmyown
Profile Blog Joined April 2009
United States4291 Posts
Last Edited: 2010-09-08 14:28:23
September 08 2010 14:11 GMT
#6
$i references subpatterns, which are denoted by parentheses.

His problem is that while regex returns these subpatterns and even use them in replacement, it's sort of a black box so you can't arbitrarily modify these subpatterns and replace them.

Most straightforward way I can think of, save the matches, then replace the patterns with a non-present pattern, split the string by the new pattern. Then concatenate the pieces with the modified pattern matches.

$original_string;
$final_string = "";
$match = regular_expression_match_all($original_string, $pattern)
$pattern_replaced_string = regular_expression_replace( $original_string, $pattern, "ARTOSISJOINSC2TERRAN" )
$pieces_array = split( $pattern_replaced_string, "ARTOSISJOINSC2TERRAN" )

foreach ( $pieces_array as $piece using index $i ) {
$final_string .= $piece . f( $match[i] );
}

of course there's one more piece than match, but whatever.
AntiLegend
Profile Joined September 2010
Germany247 Posts
September 08 2010 14:42 GMT
#7
instead of directly using string.replace, consider working with a regexp object. see http://www.regular-expressions.info/javascript.html for further information.
vek
Profile Joined March 2010
Australia936 Posts
September 08 2010 14:50 GMT
#8
Your question is incredibly confusing... Try to at least provide a sample of the string you are trying to parse and the expected result.

http://www.gskinner.com/RegExr/ is a good tool for building/testing regex. If you can explain your problem more clearly I can try to help further.
Count9
Profile Blog Joined May 2009
China10928 Posts
September 08 2010 14:54 GMT
#9
Maybe the /g flag causes the capture groups to not output strings, does it replace one time with no /g flag at the end? If it can do that just put that in an empty while loop or something.
cafaro
Profile Joined November 2008
Netherlands32 Posts
Last Edited: 2010-09-08 15:15:47
September 08 2010 15:01 GMT
#10

var str = "foo bar"
var regex = /\w/g;

str.replace(regex, processMatch);

function processMatch(substr, p1) {

// Process your match here
return p1 + " ";

}


The inline replacement function already receives the $[...] patterns as it's arguments.

You only have to define these in the declaration of this function.

More information: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter
Osmoses
Profile Blog Joined October 2008
Sweden5302 Posts
Last Edited: 2010-09-08 15:29:05
September 08 2010 15:28 GMT
#11
+ Show Spoiler +
On September 09 2010 00:01 cafaro wrote:

var str = "foo bar"
var regex = /\w/g;

str.replace(regex, processMatch);

function processMatch(substr, p1) {

// Process your match here
return p1 + " ";

}


The inline replacement function already receives the $[...] patterns as it's arguments.

You only have to define these in the declaration of this function.

More information: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter

That's awesome, will definitely remember that for the future
Excuse me hun, but what is your name? Vivian? I woke up next to you naked and, uh, did we, um?
Please log in or register to reply.
Live Events Refresh
Wardi Open
11:00
#91
WardiTV1119
IntoTheiNu 1024
Rex180
Ryung 99
Liquipedia
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
Rex 180
Ryung 99
mouzStarbuck 34
SHIN 19
StarCraft: Brood War
Shuttle 3479
Zeus 1829
Sea 1465
Mini 1091
EffOrt 874
Horang2 558
Soma 500
Soulkey 354
Light 309
actioN 251
[ Show more ]
Snow 191
ToSsGirL 131
Rush 125
Free 112
Pusan 88
hero 87
Hyun 60
Sea.KH 51
[sc1f]eonzerg 43
scan(afreeca) 42
sorry 38
Aegong 37
Sacsri 27
Barracks 25
soO 24
HiyA 21
Noble 18
Shine 18
yabsab 13
Bale 13
zelot 12
GoRush 12
Terrorterran 11
ajuk12(nOOB) 8
Dota 2
Dendi1261
XcaliburYe258
syndereN15
Counter-Strike
fl0m4642
olofmeister2012
byalli412
kRYSTAL_20
Super Smash Bros
Mew2King76
Other Games
Gorgc2227
Trikslyr1677
B2W.Neo717
hiko651
Lowko618
XaKoH 224
Hui .77
amsayoshi43
MindelVK8
Organizations
StarCraft: Brood War
UltimateBattle 1146
Other Games
BasetradeTV155
StarCraft 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
[ Show 11 non-featured ]
StarCraft 2
• AfreecaTV YouTube
• intothetv
• Kozan
• IndyKCrew
• LaughNgamezSOOP
• Migwel
• sooper7s
StarCraft: Brood War
• BSLYoutube
• STPLYoutube
• ZZZeroYoutube
League of Legends
• TFBlade389
Upcoming Events
Monday Night Weeklies
2h 46m
OSC
10h 46m
Replay Cast
1d 19h
The PondCast
2 days
Replay Cast
3 days
OSC
3 days
CranKy Ducklings
3 days
BSL22 NKC (BSL vs China)
5 days
XuanXuan vs Jaystar
Mihu vs Messiah
eOnzErG vs Dewalt
Bonyth vs Jaystar
TerrOr vs Messiah
XuanXuan vs Mihu
eOnzErG vs Jaystar
Patches Events
6 days
BSL22 NKC (BSL vs China)
6 days
Dewalt vs Messiah
Bonyth vs Mihu
TerrOr vs XuanXuan
eOnzErG vs Messiah
Jaystar vs Mihu
Dewalt vs XuanXuan
Bonyth vs TerrOr
[ Show More ]
WardiTV Weekly
6 days
Liquipedia Results

Completed

Acropolis #4 - GSB
uThermal 2v2 2026 Main Event
Heroes Pulsing #1

Ongoing

IPSL Spring 2026
KCM Race Survival 2026 Season 2
Acropolis #4
CSCL: Masked Kings S4
YSL S3
BSL 22 Non-Korean Championship
SCTL 2026 Spring
Maestros of the Game 2
WardiTV Spring 2026
Murky Cup 2026
Heroes Pulsing #2
IEM Cologne Major 2026
Stake Ranked Episode 2
CS Asia Championships 2026
Asian Champions League 2026
IEM Atlanta 2026
PGL Astana 2026
BLAST Rivals Spring 2026
IEM Rio 2026
PGL Bucharest 2026
Stake Ranked Episode 1

Upcoming

CSLAN 4
Blizzard Classic Cup 2026
Kung Fu Cup 2026 Grand Finals
RSL Revival: Season 6
CranK Gathers Season 4: BW vs SC2 Team League
HSC XXIX
Douyu Cup 2026
BCC 2026
Heroes Pulsing #3
BLAST Open Fall 2026
Esports World Cup 2026
BLAST Bounty Summer 2026
BLAST Bounty Summer Qual
Stake Ranked Episode 3
XSE Pro League 2026
TLPD

1. ByuN
2. TY
3. Dark
4. Solar
5. Stats
6. Nerchio
7. sOs
8. soO
9. INnoVation
10. Elazer
1. Rain
2. Flash
3. EffOrt
4. Last
5. Bisu
6. Soulkey
7. Mini
8. Sharp
Sidebar Settings...

Advertising | Privacy Policy | Terms Of Use | Contact Us

Original banner artwork: Jim Warren
The contents of this webpage are copyright © 2026 TLnet. All Rights Reserved.