简体   繁体   中英

Javascript - remove a string in the middle of a string

Thank you everyone for your great help !

Sorry, I have to edit my question.

What if the "-6.7.8" is a random string that starts with "-" and has two "." between random numbers? such as "-609.7892.805667"?

===============

I am new to JavaScript, could someone help me for the following question?

I have a string AB.CD.1.23.3-609.7.8.EF.HI

I would like to break it into two strings: AB.CD.1.2.3.EF.HI (remove -609.7.8 in the middle) and AB.CD.6.7.8.EF.HI (remove 1.23.3- in the middle).

Is there an easy way to do it?

Thank you very much!

var s = "AB.CD.1.23.3-609.7.8.EF.HI";
var a = s.replace("-609.7.8","");
var b = s.replace("1.23.3-","");
console.log(a); //AB.CD.1.23.3.EF.HI
console.log(b); //AB.CD.609.7.8.EF.HI 

You could use str.replace(); var str = "AB.CD.1.2.3-6.7.8.EF.HI"; var str1 = str.replace("-6.7.8",""); // should return "AB.CD.1.2.3.EF.HI" var str2 = str.replace("1.2.3-",""); // should return "AB.CD.6.7.8.EF.HI" str.replace(); var str = "AB.CD.1.2.3-6.7.8.EF.HI"; var str1 = str.replace("-6.7.8",""); // should return "AB.CD.1.2.3.EF.HI" var str2 = str.replace("1.2.3-",""); // should return "AB.CD.6.7.8.EF.HI"

Use split() in String.prototype.split

var myString = "AB.CD.1.23.3-609.7.8.EF.HI";
var splits1 = myString.split("-609.7.8");
console.log(splits1);
var splits2 = myString.split("1.23.3-");
console.log(splits2);

With regular expressions:

s = 'AB.CD.1.23.3-609.7.8.EF.HI'
var re = /([A-Z]+\.[A-Z]+)\.([0-9]+\.[0-9]+.[0-9]+)-([0-9]+\.[0-9]+.[0-9]+)\.([A-Z]+\.[A-Z]+)/
matches = re.exec(s)
a = matches[1] + '.' + matches[2] + '.' + matches[4] // "AB.CD.1.23.3.EF.HI"
b = matches[1] + '.' + matches[3] + '.' + matches[4] // "AB.CD.609.7.8.EF.HI"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM