• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EDT 22:55
CEST 04:55
KST 11:55
  • 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
Code S Season 1 - RO12 Group A: Rogue, Percival, Solar, Zoun8[ASL21] Ro8 Preview Pt1: Inheritors16[ASL21] Ro16 Preview Pt2: All Star10Team Liquid Map Contest #22 - The Finalists20[ASL21] Ro16 Preview Pt1: Fresh Flow9
Community News
2026 GSL Season 1 Qualifiers25Maestros of the Game 2 announced92026 GSL Tour plans announced15Weekly Cups (April 6-12): herO doubles, "Villains" prevail1MaNa leaves Team Liquid25
StarCraft 2
General
Code S Season 1 - RO12 Group A: Rogue, Percival, Solar, Zoun Team Liquid Map Contest #22 - The Finalists Blizzard Classic Cup @ BlizzCon 2026 - $100k prize pool MaNa leaves Team Liquid Maestros of the Game 2 announced
Tourneys
SEL Masters #6 - Solar vs Classic (SC: Evo) $5,000 WardiTV TLMC tournament - Presented by Monster Energy GSL Code S Season 1 (2026) FSL Season 10 Individual Championship WardiTV Spring Cup
Strategy
Custom Maps
[D]RTS in all its shapes and glory <3 [A] Nemrods 1/4 players [M] (2) Frigid Storage
External Content
The PondCast: SC2 News & Results Mutation # 523 Firewall Mutation # 522 Flip My Base Mutation # 521 Memorable Boss
Brood War
General
BW General Discussion JaeDong's ASL S21 Ro16 Post-Review ASL21 General Discussion Leta's ASL S21 Ro.16 review [ASL21] Ro8 Preview Pt1: Inheritors
Tourneys
[ASL21] Ro8 Day 1 [BSL22] RO16 Group Stage - 02 - 10 May Korean KCM Race Survival 2026 Season 2 [ASL21] Ro8 Day 2
Strategy
Fighting Spirit mining rates Simple Questions, Simple Answers What's the deal with APM & what's its true value Any training maps people recommend?
Other Games
General Games
Stormgate/Frost Giant Megathread Daigo vs Menard Best of 10 Nintendo Switch Thread Dawn of War IV Diablo IV
Dota 2
The Story of Wings Gaming
League of Legends
G2 just beat GenG in First stand
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 Mafia Game Mode Feedback/Ideas TL Mafia Community Thread Five o'clock TL Mafia
Community
General
US Politics Mega-thread European Politico-economics QA Mega-thread Russo-Ukrainian War Thread 3D technology/software discussion Canadian Politics Mega-thread
Fan Clubs
The IdrA Fan Club
Media & Entertainment
[Manga] One Piece Anime Discussion Thread [Req][Books] Good Fantasy/SciFi books Movie Discussion!
Sports
2024 - 2026 Football Thread Formula 1 Discussion McBoner: A hockey love story
World Cup 2022
Tech Support
streaming software Strange computer issues (software) [G] How to Block Livestream Ads
TL Community
The Automated Ban List
Blogs
Sexual Health Of Gamers
TrAiDoS
lurker extra damage testi…
StaticNine
Broowar part 2
qwaykee
Funny Nicknames
LUCKY_NOOB
Iranian anarchists: organize…
XenOsky
Customize Sidebar...

Website Feedback

Closed Threads



Active: 2155 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
Replay Cast
00:00
StarCraft Evolution League #21
CranKy Ducklings102
LiquipediaDiscussion
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
RuFF_SC2 158
SpeCial 120
Nina 108
StarCraft: Brood War
GuemChi 6261
910 55
NaDa 30
Dota 2
NeuroSwarm419
monkeys_forever324
League of Legends
Doublelift3541
JimRising 625
Counter-Strike
taco 897
Other Games
summit1g7558
C9.Mang0548
WinterStarcraft335
ViBE69
Maynarde65
Organizations
Other Games
gamesdonequick1310
BasetradeTV76
Dota 2
PGL Dota 2 - Main Stream56
StarCraft 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
[ Show 15 non-featured ]
StarCraft 2
• CranKy Ducklings SOOP5
• AfreecaTV YouTube
• intothetv
• Kozan
• IndyKCrew
• LaughNgamezSOOP
• Migwel
• sooper7s
• swagsyndrome_ 0
StarCraft: Brood War
• BSLYoutube
• STPLYoutube
• ZZZeroYoutube
League of Legends
• Stunt243
• Lourlo227
Other Games
• Scarra1108
Upcoming Events
GSL
6h 35m
Cure vs TriGGeR
ByuN vs Bunny
KCM Race Survival
7h 5m
Big Gabe
9h 5m
Replay Cast
21h 5m
Replay Cast
1d 6h
Escore
1d 7h
OSC
1d 10h
Replay Cast
1d 21h
Replay Cast
2 days
RSL Revival
2 days
[ Show More ]
IPSL
2 days
Ret vs Art_Of_Turtle
Radley vs TBD
BSL
2 days
Replay Cast
2 days
RSL Revival
3 days
uThermal 2v2 Circuit
3 days
BSL
3 days
IPSL
3 days
eOnzErG vs TBD
G5 vs Nesh
Replay Cast
4 days
Wardi Open
4 days
Afreeca Starleague
4 days
Jaedong vs Light
Monday Night Weeklies
4 days
Replay Cast
4 days
Sparkling Tuna Cup
5 days
Afreeca Starleague
5 days
Snow vs Flash
GSL
6 days
Replay Cast
6 days
Liquipedia Results

Completed

Proleague 2026-04-28
WardiTV TLMC #16
Nations Cup 2026

Ongoing

BSL Season 22
ASL Season 21
CSL 2026 SPRING (S20)
IPSL Spring 2026
KCM Race Survival 2026 Season 2
StarCraft2 Community Team League 2026 Spring
2026 GSL S1
BLAST Rivals Spring 2026
IEM Rio 2026
PGL Bucharest 2026
Stake Ranked Episode 1
BLAST Open Spring 2026
ESL Pro League S23 Finals
ESL Pro League S23 Stage 1&2
PGL Cluj-Napoca 2026

Upcoming

Escore Tournament S2: W5
KK 2v2 League Season 1
Acropolis #4
BSL 22 Non-Korean Championship
CSLAN 4
Kung Fu Cup 2026 Grand Finals
HSC XXIX
uThermal 2v2 2026 Main Event
Maestros of the Game 2
2026 GSL S2
RSL Revival: Season 5
XSE Pro League 2026
IEM Cologne Major 2026
Stake Ranked Episode 2
CS Asia Championships 2026
IEM Atlanta 2026
Asian Champions League 2026
PGL Astana 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.