用js写一个HelloWorld <=>hello world 两个 string相互转换,多举几个例子
时间: 2023-06-03 07:02:11 浏览: 49
可以使用如下代码实现:
// 将 "HelloWorld" 转换为 "hello world"
let str1 = "HelloWorld";
let newStr1 = str1.replace(/([A-Z])/g, " $1").toLowerCase();
console.log(newStr1); // 输出 "hello world"
// 将 "hello world" 转换为 "HelloWorld"
let str2 = "hello world";
let newStr2 = str2.replace(/(\b\w)/gi, function(m) { return m.toUpperCase(); });
console.log(newStr2); // 输出 "HelloWorld"
// 更多例子
console.log("OneTwoThree".replace(/([A-Z])/g, " $1").toLowerCase()); // 输出 "one two three"
console.log("longAndComplicatedString".replace(/([A-Z])/g, " $1").toLowerCase()); // 输出 "long and complicated string"
console.log("This is a sentence".replace(/(\b\w)/gi, function(m) { return m.toUpperCase(); })); // 输出 "This Is A Sentence"