• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EDT 15:11
CET 20:11
KST 04:11
  • 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
ByuL: The Forgotten Master of ZvT29Behind the Blue - Team Liquid History Book19Clem wins HomeStory Cup 289HomeStory Cup 28 - Info & Preview13Rongyi Cup S3 - Preview & Info8
Community News
BSL Season 223Vitality ends partnership with ONSYDE20Team Liquid Map Contest - Preparation Notice6Weekly Cups (Feb 23-Mar 1): herO doubles, 2v2 bonanza2Weekly Cups (Feb 16-22): MaxPax doubles0
StarCraft 2
General
GSL CK - new tournament Weekly Cups (Feb 23-Mar 1): herO doubles, 2v2 bonanza Vitality ends partnership with ONSYDE How do you think the 5.0.15 balance patch (Oct 2025) for StarCraft II has affected the game? Team Liquid Map Contest - Preparation Notice
Tourneys
RSL Season 4 announced for March-April Sparkling Tuna Cup - Weekly Open Tournament PIG STY FESTIVAL 7.0! (19 Feb - 1 Mar) $5,000 WardiTV Winter Championship 2026 Sea Duckling Open (Global, Bronze-Diamond)
Strategy
Custom Maps
Publishing has been re-enabled! [Feb 24th 2026] Map Editor closed ?
External Content
The PondCast: SC2 News & Results Mutation # 516 Specter of Death Mutation # 515 Together Forever Mutation # 514 Ulnar New Year
Brood War
General
BGH Auto Balance -> http://bghmmr.eu/ battle.net problems ASL21 General Discussion BSL Season 22 BSL 22 Map Contest — Submissions OPEN to March 10
Tourneys
[Megathread] Daily Proleagues ASL Season 21 Qualifiers March 7-8 BWCL Season 64 Announcement [BSL22] Open Qualifier #1 - Sunday 21:00 CET
Strategy
Soma's 9 hatch build from ASL Game 2 Fighting Spirit mining rates Simple Questions, Simple Answers Zealot bombing is no longer popular?
Other Games
General Games
Nintendo Switch Thread PC Games Sales Thread Path of Exile No Man's Sky (PS4 and PC) Stormgate/Frost Giant Megathread
Dota 2
Official 'what is Dota anymore' discussion The Story of Wings Gaming
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
Mafia Game Mode Feedback/Ideas Vanilla Mini Mafia TL Mafia Community Thread
Community
General
US Politics Mega-thread Mexico's Drug War Russo-Ukrainian War Thread Things Aren’t Peaceful in Palestine YouTube Thread
Fan Clubs
The IdrA Fan Club
Media & Entertainment
[Manga] One Piece [Req][Books] Good Fantasy/SciFi books Anime Discussion Thread
Sports
2024 - 2026 Football Thread Cricket [SPORT] Formula 1 Discussion TL MMA Pick'em Pool 2013
World Cup 2022
Tech Support
Laptop capable of using Photoshop Lightroom?
TL Community
The Automated Ban List
Blogs
FS++
Kraekkling
Shocked by a laser…
Spydermine0240
Gaming-Related Deaths
TrAiDoS
ONE GREAT AMERICAN MARINE…
XenOsky
Unintentional protectionism…
Uldridge
ASL S21 English Commentary…
namkraft
Customize Sidebar...

Website Feedback

Closed Threads



Active: 2567 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
Monday Night Weeklies
17:00
#43
TKL 438
SteadfastSC408
IndyStarCraft 194
BRAT_OK 154
LiquipediaDiscussion
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
TKL 438
SteadfastSC 408
IndyStarCraft 194
UpATreeSC 176
BRAT_OK 154
MaxPax 154
JuggernautJason69
StarCraft: Brood War
Dewaltoss 121
ggaemo 32
Dota 2
Gorgc6627
qojqva1587
monkeys_forever155
Counter-Strike
pashabiceps4243
byalli703
Heroes of the Storm
Liquid`Hasu140
MindelVK10
Other Games
gofns34583
tarik_tv12531
Grubby2210
Liquid`RaSZi2097
FrodaN2042
singsing1801
Beastyqt665
ArmadaUGS170
mouzStarbuck151
C9.Mang0135
QueenE108
Hui .76
Trikslyr64
ZombieGrub1
Organizations
Dota 2
PGL Dota 2 - Main Stream8495
PGL Dota 2 - Secondary Stream5294
Other Games
gamesdonequick1809
StarCraft 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
sctven
[ Show 16 non-featured ]
StarCraft 2
• kabyraGe 198
• Adnapsc2 9
• AfreecaTV YouTube
• intothetv
• Kozan
• IndyKCrew
• LaughNgamezSOOP
• Migwel
• sooper7s
StarCraft: Brood War
• FirePhoenix7
• BSLYoutube
• STPLYoutube
• ZZZeroYoutube
League of Legends
• TFBlade1376
• Shiphtur385
Other Games
• imaqtpie1109
Upcoming Events
OSC
4h 49m
Wardi Open
16h 49m
PiGosaur Monday
1d 4h
WardiTV Team League
1d 16h
Replay Cast
2 days
The PondCast
2 days
WardiTV Team League
2 days
Replay Cast
3 days
Replay Cast
4 days
CranKy Ducklings
4 days
[ Show More ]
WardiTV Team League
4 days
Replay Cast
5 days
Sparkling Tuna Cup
5 days
WardiTV Team League
5 days
Replay Cast
6 days
Replay Cast
6 days
Wardi Open
6 days
Monday Night Weeklies
6 days
Liquipedia Results

Completed

ASL Season 21: Qualifier #2
WardiTV Winter 2026
Underdog Cup #3

Ongoing

KCM Race Survival 2026 Season 1
Jeongseon Sooper Cup
Spring Cup 2026
BSL Season 22
RSL Revival: Season 4
Nations Cup 2026
ESL Pro League S23 Stage 1&2
PGL Cluj-Napoca 2026
IEM Kraków 2026
BLAST Bounty Winter 2026
BLAST Bounty Winter Qual

Upcoming

ASL Season 21
Acropolis #4 - TS6
Acropolis #4
IPSL Spring 2026
CSLAN 4
HSC XXIX
uThermal 2v2 2026 Main Event
Bellum Gens Elite Stara Zagora 2026
NationLESS Cup
CS Asia Championships 2026
Asian Champions League 2026
IEM Atlanta 2026
PGL Astana 2026
BLAST Rivals Spring 2026
CCT Season 3 Global Finals
IEM Rio 2026
PGL Bucharest 2026
Stake Ranked Episode 1
BLAST Open Spring 2026
ESL Pro League S23 Finals
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.