问题
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
回答1:
Three issues there:
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 theg
flag.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."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, ';');
来源:https://stackoverflow.com/questions/26419590/replace-multiple-semicolon-to-single-one-in-javascript