Replace multiple semicolon to single one in JavaScript

我们两清 提交于 2021-02-17 02:47:13

问题


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:

  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, ';');


来源:https://stackoverflow.com/questions/26419590/replace-multiple-semicolon-to-single-one-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!