[英]Replace multiple semicolon to single one in JavaScript
I try to remove multiple semicolon (;) replace to single semicolon (;) in javascrpt.我尝试在 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:那里的三个问题:
When you pass a string into replace
as the first argument, only the first occurrence is replaced.当您将字符串作为第一个参数传递给
replace
,只会替换第一个出现的位置。 To do a global replace, you have to use a regular expression with the g
flag.要进行全局替换,您必须使用带有
g
标志的正则表达式。
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."正则表达式在这里也有帮助,特别是
/;+/g
表示“一个或多个;
字符,在字符串中全局存在”。
replace
doesn't change the string you call it on, it returns a new string with the changes. replace
不会更改您调用它的字符串,它会返回一个带有更改的新字符串。 To remember what it does, you have to assign the result somewhere.要记住它的作用,您必须将结果分配到某个地方。
So:所以:
test = test.replace(/;+/g, ';');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.