ISTANBUL — Militias loyal to the Syrian government swept into the northwestern enclave of Afrin on Thursday in support of Kurdish militias, reclaiming the territory and stealing a march on Turkish forces that have been battling toward the city for nearly a month.

Television broadcasts and social media postings showed crowds celebrating in the main square of the city of Afrin, waving flags and holding posters of President Bashar al-Assad of Syria and the Kurdish militant leader Abdullah Ocalan, who is imprisoned in Turkey on terrorism charges.

The entry into Afrin of forces loyal to Mr. Assad — the result of a deal between the Syrian government and Kurdish militias, with the backing of Iran and Russia — has harmed Turkey’s ambitions in Syria. It is one of many setbacks that Turkey’s president, Recep Tayyip Erdogan, has experienced throughout the seven-year Syrian civil war.

“It’s not something Turkey is happy with at all,” said Michael Stephens, who studies the Middle East at the Royal United Services Institute in London. “It limits Turkish strategic options.” Turkey has made it clear that if attacked by pro-government forces, its forces will strike back, he said.