• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EDT 08:43
CEST 14:43
KST 21:43
  • 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
[ASL20] Ro24 Preview Pt1: Runway132v2 & SC: Evo Complete: Weekend Double Feature4Team Liquid Map Contest #21 - Presented by Monster Energy9uThermal's 2v2 Tour: $15,000 Main Event18Serral wins EWC 202549
Community News
Maestros of The Game—$20k event w/ live finals in Paris23Weekly Cups (Aug 11-17): MaxPax triples again!13Weekly Cups (Aug 4-10): MaxPax wins a triple6SC2's Safe House 2 - October 18 & 195Weekly Cups (Jul 28-Aug 3): herO doubles up6
StarCraft 2
General
What mix of new and old maps do you want in the next 1v1 ladder pool? (SC2) : 2v2 & SC: Evo Complete: Weekend Double Feature Geoff 'iNcontroL' Robinson has passed away The GOAT ranking of GOAT rankings RSL Revival patreon money discussion thread
Tourneys
RSL: Revival, a new crowdfunded tournament series Maestros of The Game—$20k event w/ live finals in Paris Sparkling Tuna Cup - Weekly Open Tournament Monday Nights Weeklies Master Swan Open (Global Bronze-Master 2)
Strategy
Custom Maps
External Content
Mutation # 487 Think Fast Mutation # 486 Watch the Skies Mutation # 485 Death from Below Mutation # 484 Magnetic Pull
Brood War
General
BGH Auto Balance -> http://bghmmr.eu/ Joined effort Flash On His 2010 "God" Form, Mind Games, vs JD New season has just come in ladder BW General Discussion
Tourneys
[ASL20] Ro24 Group B [ASL20] Ro24 Group C BWCL Season 63 Announcement [CSLPRO] It's CSLAN Season! - Last Chance
Strategy
Simple Questions, Simple Answers Fighting Spirit mining rates [G] Mineral Boosting Muta micro map competition
Other Games
General Games
Nintendo Switch Thread General RTS Discussion Thread Dawn of War IV Path of Exile Stormgate/Frost Giant Megathread
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
Heroes of StarCraft mini-set
TL Mafia
TL Mafia Community Thread Vanilla Mini Mafia
Community
General
US Politics Mega-thread Russo-Ukrainian War Thread The year 2050 Things Aren’t Peaceful in Palestine European Politico-economics QA Mega-thread
Fan Clubs
INnoVation Fan Club SKT1 Classic Fan Club!
Media & Entertainment
Anime Discussion Thread Movie Discussion! [Manga] One Piece [\m/] Heavy Metal Thread
Sports
2024 - 2026 Football Thread TeamLiquid Health and Fitness Initiative For 2023 Formula 1 Discussion
World Cup 2022
Tech Support
High temperatures on bridge(s) Gtx660 graphics card replacement Installation of Windows 10 suck at "just a moment"
TL Community
The Automated Ban List TeamLiquid Team Shirt On Sale
Blogs
Evil Gacha Games and the…
ffswowsucks
Breaking the Meta: Non-Stand…
TrAiDoS
INDEPENDIENTE LA CTM
XenOsky
[Girl blog} My fema…
artosisisthebest
Sharpening the Filtration…
frozenclaw
ASL S20 English Commentary…
namkraft
Customize Sidebar...

Website Feedback

Closed Threads



Active: 1693 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
SC Evo League
12:00
S2 Championship: Ro16 Day 2
IndyStarCraft 145
SteadfastSC60
EnkiAlexander 31
IntoTheiNu 12
Liquipedia
WardiTV Summer Champion…
11:00
Playoffs Day 1
ByuN vs herO
MaxPax vs Zoun
Clem vs NightMare
WardiTV799
Liquipedia
Sparkling Tuna Cup
10:00
Weekly #103
Solar vs ShoWTimELIVE!
ByuN vs TBD
CranKy Ducklings313
LiquipediaDiscussion
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
IndyStarCraft 145
Rex 120
BRAT_OK 94
ProTech79
SteadfastSC 60
MindelVK 35
StarCraft: Brood War
Britney 42035
Larva 913
Killer 594
Pusan 487
PianO 432
Hyun 412
Last 309
ggaemo 289
Mini 284
Soma 233
[ Show more ]
Hyuk 229
firebathero 219
Rush 199
Mind 197
Barracks 158
Sea.KH 49
soO 35
ajuk12(nOOB) 27
Free 25
Noble 15
Icarus 15
HiyA 15
Sacsri 10
Dota 2
Gorgc7800
qojqva1345
XcaliburYe460
Pyrionflax201
Fuzer 148
League of Legends
Dendi839
Counter-Strike
summit1g8811
olofmeister1897
Super Smash Bros
Mew2King66
Heroes of the Storm
Khaldor207
Other Games
singsing2080
B2W.Neo763
RotterdaM222
byalli185
rGuardiaN43
Organizations
StarCraft 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
sctven
[ Show 15 non-featured ]
StarCraft 2
• Reevou 12
• intothetv
• AfreecaTV YouTube
• Kozan
• IndyKCrew
• LaughNgamezSOOP
• Migwel
• sooper7s
StarCraft: Brood War
• BSLYoutube
• STPLYoutube
• ZZZeroYoutube
Dota 2
• C_a_k_e 2851
• WagamamaTV369
League of Legends
• Jankos2406
• Nemesis1776
Upcoming Events
Chat StarLeague
3h 17m
Razz vs Julia
StRyKeR vs ZZZero
Semih vs TBD
Replay Cast
11h 17m
Afreeca Starleague
21h 17m
Queen vs HyuN
EffOrt vs Calm
Wardi Open
22h 17m
RotterdaM Event
1d 2h
Replay Cast
1d 11h
Afreeca Starleague
1d 21h
Rush vs TBD
Jaedong vs Mong
WardiTV Summer Champion…
1d 22h
PiGosaur Monday
2 days
Afreeca Starleague
2 days
herO vs TBD
Royal vs Barracks
[ Show More ]
Replay Cast
3 days
The PondCast
3 days
WardiTV Summer Champion…
3 days
Replay Cast
4 days
LiuLi Cup
4 days
Cosmonarchy
5 days
OyAji vs Sziky
Sziky vs WolFix
WolFix vs OyAji
BSL Team Wars
5 days
Team Hawk vs Team Dewalt
BSL Team Wars
5 days
Team Hawk vs Team Bonyth
SC Evo League
5 days
[BSL 2025] Weekly
6 days
SC Evo League
6 days
Liquipedia Results

Completed

Jiahua Invitational
uThermal 2v2 Main Event
HCC Europe

Ongoing

Copa Latinoamericana 4
BSL 20 Team Wars
KCM Race Survival 2025 Season 3
BSL 21 Qualifiers
ASL Season 20
CSL Season 18: Qualifier 1
Acropolis #4 - TS1
CSLAN 3
SEL Season 2 Championship
WardiTV Summer 2025
Esports World Cup 2025
BLAST Bounty Fall 2025
BLAST Bounty Fall Qual
IEM Cologne 2025
FISSURE Playground #1
BLAST.tv Austin Major 2025

Upcoming

CSL Season 18: Qualifier 2
CSL 2025 AUTUMN (S18)
LASL Season 20
BSL Season 21
BSL 21 Team A
Chzzk MurlocKing SC1 vs SC2 Cup #2
RSL Revival: Season 2
Maestros of the Game
EC S1
Sisters' Call Cup
IEM Chengdu 2025
PGL Masters Bucharest 2025
MESA Nomadic Masters Fall
Thunderpick World Champ.
CS Asia Championships 2025
Roobet Cup 2025
ESL Pro League S22
StarSeries Fall 2025
FISSURE Playground #2
BLAST Open Fall 2025
BLAST Open Fall 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 © 2025 TLnet. All Rights Reserved.