如何让这个正则表达式替换所有字符,而不仅仅是第一个? [英] How to make this regex replace work on all characters, not just the first?

查看:34
本文介绍了如何让这个正则表达式替换所有字符,而不仅仅是第一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用连字符替换字符串中的所有空格.我试过这个:

I’m trying to replace all spaces within a string with hyphens. I tried this:

h3Text.replace(/\s/, '-');

但它只替换空格的第一个实例,而不替换它之后的实例.使它替换所有空格的正则表达式是什么?

But it only replaces the first instance of a space and not the ones after it. What is the regex to make it replace all empty spaces?

推荐答案

try

h3Text.replace(/\s/g, '-');

g 标志是这里的关键.表示全局替换,即全部替换

the g flag is key here. it means global replace, ie replace all

这篇关于如何让这个正则表达式替换所有字符,而不仅仅是第一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆