中将多个分号替换为单个分号

中将多个分号替换为单个分号

本文介绍了在 JavaScript 中将多个分号替换为单个分号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在 javascrpt 中删除多个分号 (;) 替换为单个分号 (;).

代码:

var test ="test1;;test2;;;test3;;;;test4;;;;test5;;;;;test6;;;;;;test7;;;;;;;test8;;;;;;;;;test9"test.replace(";;",";")

但没有得到正确的输出.(必须使用替换)如果有任何解决方案

我需要这样的输出:

test1;test2;test3;test4;test5;test6;test7;test8;test9
解决方案

三个问题:

  1. 当您将字符串作为第一个参数传递给 replace 时,只会替换第一个出现的位置.要进行全局替换,您必须使用带有 g 标志的正则表达式.

  2. 如果它完成整个字符串,您只需将 ;; 替换为 ;,所以如果您有 ;;;; 你最终会得到 ;; (两者都被替换).正则表达式在这里也有帮助,特别是 /;+/g 表示一个或多个 ;字符,在字符串中全局存在.">

  3. replace 不会更改您调用它的字符串,它返回一个带有更改的新字符串.要记住它的作用,您必须将结果分配到某处.

所以:

test = test.replace(/;+/g, ';');

I try to remove multiple semicolon (;) replace to single semicolon (;) in javascrpt.

code:

var test ="test1;;test2;;;test3;;;;test4;;;;test5;;;;;test6;;;;;;test7;;;;;;;test8;;;;;;;;test9"
test.replace(";;",";")

But not get proper output.(must use replace)if any solution

I need output like :

test1;test2;test3;test4;test5;test6;test7;test8;test9
解决方案

Three issues there:

  1. When you pass a string into replace as the first argument, only the first occurrence is replaced. To do a global replace, you have to use a regular expression with the g flag.

  2. If it did the whole string, you'd only replace ;; with ;, so if you had ;;;; you'd end up with ;; (each of the two being replaced). A regex also helps here, specifically /;+/g which means "one or more ; characters, globally in the string."

  3. replace doesn't change the string you call it on, it returns a new string with the changes. To remember what it does, you have to assign the result somewhere.

So:

test = test.replace(/;+/g, ';');

这篇关于在 JavaScript 中将多个分号替换为单个分号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 10:36