给出:var str = "i wondered what a scattered brained computer does to remain sane"
我希望:
var output to read = ""i" "wonder" "what" "a" "scattered" "brained" "computer" "does" "to" "remain" "sane""
您认为最佳行动是什么?
答案 0 :(得分:2)
最简单的答案如下:
var output = str.split(" ");
答案 1 :(得分:2)
您可以使用String#replace
找到所需的解决方案,它会将每个单词用引号"
换行。
const str = 'I wondered what a scattered brained computer does to remain sane';
let res = str.replace(/\w+/g, '"$&"');
console.log(res);
答案 2 :(得分:0)
JavaScript中有一些有用的内置方法:
String.prototype.split()
- 对一个字符串执行,它将它“拆分”为所提供的子字符串的每个实例的数组。即'abc'.split('b'); // ['a','c']
Array.prototype.join()
- 在一个数组上执行,它将每个元素与给定的字符串“连接”起来。即['a','c'].join('d'); // 'adc'
那你怎么用这些呢?简单!
var str = "i wondered what a scattered brained computer does to remain sane";
var output = str.split(" ").join('" "'); // Note: javascript strings can be delimited with both `'` and `"`, which comes in handy!
console.log('"' + output + '"'); // Finally, add the missing `"` on the first and last word and print
那么如果有多个空格会怎么样?如果输入与var str = "Hello world!"
类似(请注意"hello"
和"world"
之间有2个空格)。
有一种更高级的方法可以在名为Regular Expressions的编程中选择字符串的某些部分,它们可能会让人感到困惑和棘手,但如果使用得当它们会很强大。这将允许我们在单词之间的任意数量的空格上拆分字符串,因此您不会在输出中显示""
之类的内容。
var str = "Hello world!";
var output = str.trim().split(/\s+/g).join('" "'); // Here we use the .trim() method to remove any spaces at the beginning or the end of the string, we split on as many spaces in a row as we can, then join
console.log('regex: "' + output + '"');
// what would the old method look like?
var str = "Hello world!";
console.log('no regex: "' + str.split(' ').join('" "') + '"');