• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EST 21:46
CET 03:46
KST 11:46
  • 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
RSL Revival - 2025 Season Finals Preview8RSL Season 3 - Playoffs Preview0RSL Season 3 - RO16 Groups C & D Preview0RSL Season 3 - RO16 Groups A & B Preview2TL.net Map Contest #21: Winners12
Community News
$21,000 Rongyi Cup Season 3 announced (Jan 22-Feb 7)11Weekly Cups (Dec 29-Jan 4): Protoss rolls, 2v2 returns6[BSL21] Non-Korean Championship - Starts Jan 103SC2 All-Star Invitational: Jan 17-1822Weekly Cups (Dec 22-28): Classic & MaxPax win, Percival surprises3
StarCraft 2
General
Spontaneous hotkey change zerg Chinese SC2 server to reopen; live all-star event in Hangzhou Weekly Cups (Dec 29-Jan 4): Protoss rolls, 2v2 returns SC2 All-Star Invitational: Jan 17-18 Weekly Cups (Dec 22-28): Classic & MaxPax win, Percival surprises
Tourneys
$21,000 Rongyi Cup Season 3 announced (Jan 22-Feb 7) WardiTV Winter Cup WardiTV Mondays SC2 AI Tournament 2026 OSC Season 13 World Championship
Strategy
Simple Questions Simple Answers
Custom Maps
Map Editor closed ?
External Content
Mutation # 508 Violent Night Mutation # 507 Well Trained Mutation # 506 Warp Zone Mutation # 505 Rise From Ashes
Brood War
General
I would like to say something about StarCraft Potential ASL qualifier breakthroughs? BGH Auto Balance -> http://bghmmr.eu/ BW General Discussion StarCraft & BroodWar Campaign Speedrun Quest
Tourneys
[Megathread] Daily Proleagues [BSL21] Grand Finals - Sunday 21:00 CET [BSL21] Non-Korean Championship - Starts Jan 10 SLON Grand Finals – Season 2
Strategy
Game Theory for Starcraft Simple Questions, Simple Answers Current Meta [G] How to get started on ladder as a new Z player
Other Games
General Games
Awesome Games Done Quick 2026! Mechabellum Beyond All Reason Stormgate/Frost Giant Megathread General RTS Discussion Thread
Dota 2
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 Mafia Game Mode Feedback/Ideas
Community
General
US Politics Mega-thread European Politico-economics QA Mega-thread Things Aren’t Peaceful in Palestine Russo-Ukrainian War Thread Trading/Investing Thread
Fan Clubs
White-Ra Fan Club
Media & Entertainment
Anime Discussion Thread
Sports
2024 - 2026 Football Thread Formula 1 Discussion
World Cup 2022
Tech Support
Computer Build, Upgrade & Buying Resource Thread
TL Community
The Automated Ban List TL+ Announced
Blogs
My 2025 Magic: The Gathering…
DARKING
Physical Exercise (HIIT) Bef…
TrAiDoS
Life Update and thoughts.
FuDDx
How do archons sleep?
8882
James Bond movies ranking - pa…
Topin
Customize Sidebar...

Website Feedback

Closed Threads



Active: 3037 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
Next event in 6h 14m
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
White-Ra 217
StarCraft: Brood War
Artosis 838
Sharp 470
Shine 83
Bale 83
Sexy 75
Noble 45
zelot 42
GoRush 21
Hm[arnc] 9
Dota 2
monkeys_forever107
NeuroSwarm85
Counter-Strike
summit1g9946
fl0m5726
minikerr42
Other Games
tarik_tv6647
Liquid`RaSZi3220
JimRising 439
KnowMe74
ViBE55
Liquid`Ken12
Ketroc11
Organizations
Other Games
gamesdonequick5144
StarCraft 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
sctven
[ Show 15 non-featured ]
StarCraft 2
• Hupsaiya 106
• AfreecaTV YouTube
• intothetv
• Kozan
• IndyKCrew
• LaughNgamezSOOP
• Migwel
• sooper7s
StarCraft: Brood War
• RayReign 28
• BSLYoutube
• STPLYoutube
• ZZZeroYoutube
Dota 2
• WagamamaTV773
League of Legends
• Rush482
Other Games
• Scarra1939
Upcoming Events
Replay Cast
6h 14m
Wardi Open
11h 14m
Monday Night Weeklies
14h 14m
WardiTV Invitational
1d 9h
WardiTV Invitational
2 days
The PondCast
3 days
OSC
3 days
OSC
4 days
All Star Teams
4 days
INnoVation vs soO
sOs vs Scarlett
uThermal 2v2 Circuit
5 days
[ Show More ]
All Star Teams
5 days
MMA vs DongRaeGu
Rogue vs Oliveira
Sparkling Tuna Cup
6 days
OSC
6 days
Liquipedia Results

Completed

Proleague 2026-01-11
Big Gabe Cup #3
NA Kuram Kup

Ongoing

C-Race Season 1
IPSL Winter 2025-26
BSL 21 Non-Korean Championship
CSL 2025 WINTER (S19)
OSC Championship Season 13
Underdog Cup #3
eXTREMESLAND 2025
SL Budapest Major 2025
ESL Impact League Season 8
BLAST Rivals Fall 2025
IEM Chengdu 2025
PGL Masters Bucharest 2025

Upcoming

Escore Tournament S1: W4
Acropolis #4
IPSL Spring 2026
Bellum Gens Elite Stara Zagora 2026
HSC XXVIII
Rongyi Cup S3
Thunderfire SC2 All-star 2025
Nations Cup 2026
BLAST Open Spring 2026
ESL Pro League Season 23
ESL Pro League Season 23
PGL Cluj-Napoca 2026
IEM Kraków 2026
BLAST Bounty Winter 2026
BLAST Bounty Winter Qual
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.