我有一个SDP文件,并将其转换为如下所示的字符串:
v=0
o=- 1443716955 1443716955 IN IP4 10.20.130.110
m=video 20000 RTP/AVP 96 // <== this line
c=IN IP4 239.0.1.2/64
a=source-filter: incl IN IP4 239.0.1.2 192.168.0.1
a=rtpmap:96 raw/90000
a=mid:primary
m=video 20000 RTP/AVP 96 // <== this line
c=IN IP4 239.0.1.3/64
a=source-filter: incl IN IP4 239.0.1.3 192.168.0.1在这行“m=video 20000 RTP/AVP 96”中,我想将'20000'更改为'4321',我编写了以下代码:
let fileds= inputString .split(/\s+/);
for(const field of fields) {
if(field === "m=video") {
}
if (field === "m=audio") {
var myflag = "au";
}
} 上面的颂歌给我一个低沉的结果:
m=video 4321 RTP/AVP 96
m=video 4321 RTP/AVP 96我只想更改它们并替换为字符串(就像新字符串),假设我需要的结果如下所示:
v=0
o=- 1443716955 1443716955 IN IP4 10.20.130.110
m=video 4321 RTP/AVP 96 // <== this line
c=IN IP4 239.0.1.2/64
a=source-filter: incl IN IP4 239.0.1.2 192.168.0.1
a=rtpmap:96 raw/90000
a=mid:primary
m=video 4321 RTP/AVP 96 //<== this line
c=IN IP4 239.0.1.3/64
a=source-filter: incl IN IP4 239.0.1.3 192.168.0.1我对java脚本完全陌生,我怎样才能替换它呢?因为我可能有另一个字符串,在这里有不同的"m=video“索引在这里'm‘在第2行,也许在下一个字符串"m=video”在第3行或第4行。
我可以使用“string.startswith('m=video')”吗?在我的代码中,它是真正的,用我得到的替换它
EX : m=video 4321 RTP/AVP 96
发布于 2020-03-28 13:50:34
我有一个例子:
或者简单地使用替换所有inputString.replace(/m=video 20000/g, "m=video 4321"),其中/m=video 20000/g中的g表示全局替换(即替换all)。
或者我们可以在每一行上映射并用stringArr.map(str => str.replace(/m=video 20000/, "m=video 4321"))替换每一行
为了使它具有动态(即允许20000以外的其他数字),我们可以创建一个RegExp:
const inputNumberString = '20000'; //can be changed
const regex = new RegExp('m=video ' + inputNumberString, 'g');
const stringReplacedAll = inputString.replace(regex, "m=video 4321")或者,如果总是存在相同的模式,但数字不同,并且希望匹配任何数字,则可以使用RegExp模式匹配,如下所示:
const inputPattern= /m=video \d{5}/g;
const stringReplacedAll = inputString.replace(inputPattern, "m=video 4321")若要更改字符串的其他部分,如IP,请执行以下操作:
const inputPattern= /m=video \d{5}/g;
const ipPattern = /c=IN IP4 \d{3}.\d.\d.\d\/\d{2}/g;
const stringReplacedAll = inputString
.replace(inputPattern, "m=video 4321")
.replace(ipPattern, "c=IN IP4 123.0.1.1/88");与'm=video '后的任意5位数匹配;
const inputString =
`v=0
o=- 1443716955 1443716955 IN IP4 10.20.130.110
m=video 20000 RTP/AVP 96 // <== this line
c=IN IP4 239.0.1.2/64
a=source-filter: incl IN IP4 239.0.1.2 192.168.0.1
a=rtpmap:96 raw/90000
a=mid:primary
m=video 20000 RTP/AVP 96 // <== this line
c=IN IP4 239.0.1.3/64
a=source-filter: incl IN IP4 239.0.1.3 192.168.0.1`;
const inputNumberString = '20000';
const inputPattern= /m=video \d{5}/g;
const ipPattern = /c=IN IP4 \d{3}.\d.\d.\d\/\d{2}/g;
const regex = new RegExp('m=video ' + inputNumberString, 'g');
const stringReplacedAll = inputString.replace(inputPattern, "m=video 4321").replace(ipPattern, "c=IN IP4 123.0.1.1/88");
console.log(stringReplacedAll);
//OR you can do it with array and map
const stringArr = inputString.split('\n');
const stringReplacedMap = stringArr.map(str => str.replace(/m=video 20000/, "m=video 4321")).join('\n');
//console.log(stringReplacedMap);
https://stackoverflow.com/questions/60901893
复制相似问题