[英]Change char in a string in JavaScript
What regular expression should I use with the 'replace()' function in JavaScript to change every occurrence of char '_' in 0, but stop working as long as finding the char '.'? 我应该使用什么正则表达式与JavaScript中的'replace()'函数一起更改0中每次出现的char'_',但只要找到char',就停止工作。'?
Example: 例:
_____323.____ ---> 00323._ _____ 323 .____ ---> 00323._
____032.0____ --> 0032.0_ ____ 032.0 ____ - > 0032.0_
Are there ways more efficient than to use 'replace()'? 有没有比使用'replace()'更有效的方法?
I am working with numbers. 我正在处理数字。 In particular, they can be both integer that float, so my string could never have two dots like in __32.12.32 or __31.34.45. 特别是,它们可以是浮动的整数,因此我的字符串永远不会有像__32.12.32或__31.34.45中的两个点。 At maximum just one dot. 最多只有一个点。
What can I add in this: 我可以在这里添加什么:
/_(?=[\d_.])/g
to also find '_' followed by nothing? 还发现'_'后面没有任何东西?
Example: 0__ or 2323.43_ 示例:0__或2323.43_
This does not work: 这不起作用:
/_(?=[\d_.$])/g
Without replace/regex: 没有替换/正则表达式:
var foo = function (str) {
var result = "", char, i, l;
for (i = 0, l = str.length; i < l; i++) {
char = str[i];
if (char == '.') {
break;
} else if (char == '_') {
result += '0';
} else {
result += str[i];
}
char = str[i];
}
return result + str.slice(i);
}
With regex: dystroy 正则表达式:破坏
Benchmark for the various answers in this post: http://jsperf.com/regex-vs-no-regex-replace 这篇文章中各种答案的基准: http : //jsperf.com/regex-vs-no-regex-replace
Unless you have some other obscure condition - 除非你有其他一些不明显的条件 -
find: 找:
_(?=[\d_.])
replace: 更换:
0
Or "To find also _ followed by nothing, example: 0__ or 2323.43_" 或者“找到_后面没有任何东西,例如:0__或2323.43_”
_(?=[\d_.]|$)
You could use lookahead assertion in regex... 你可以在regex中使用lookahead断言......
"__3_23._45_4".replace(/_(?![^.]*$)/g,'0')
Result: 003023._45_4
结果: 003023._45_4
Explanation: 说明:
/ # start regex
_ # match `_`
(?! # negative lookahead assertion
[^.]*$ # zero or more (`*`) not dots (`[^.]`) followed by the end of the string
) # end negative lookahead assertion
/g # end regex with global flag set
var str = "___345_345.4w3__w45.234__34_";
var dot = false;
str.replace(/[._]/g, function(a){
if(a=='.' || dot){
dot = true;
return a
} else {
return 0
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.