我需要从字符串开头(但仅从开头)删除下划线
例如:
list
应转换为:
toJSON(list(listName = df))
#{"listName":[{"col1":"a","col2":1},{"col1":"b","col2":2}]}
但是__Hello World
应该保留为Hello World
。
棘手的事情是我不知道下划线怎么可能有1,2或20。
答案 0 :(得分:5)
您可以将正则表达式传递给replace()
。 /^_+/,
说在字符串开头之后找到任意数量的_
:
let texts = ["__Hello World", "Hello_World", 'jello world_', '_Hello_World_', '___________Hello World']
let fixed = texts.map(t => t.replace(/^_+/, ''))
console.log(fixed)
答案 1 :(得分:2)
正则表达式非常适合此任务:
let str = "__h_e_l_l_o__"
console.log(str.replace(/^_*/, ""));
答案 2 :(得分:1)
方法01:
var str = '__Hello World';
str = str.replace(/^_*/, "");
方法02:
var str = '__Hello World';
while(str.startsWith('_')){
str = str.replace('_','');
}
console.log(str);
// Hello World