引用java脚本中字符串中的单个字符(单词)

时间:2017-07-27 21:29:30

标签: javascript arrays

学习者在这里,如果这个问题看起来很荒谬,请耐心等待。假设我试图引用字符串中的字符而不是字符串本身,我该怎么做呢? 我的意思是;

给出: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""

您认为最佳行动是什么?

3 个答案:

答案 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中有一些有用的内置方法:

  1. String.prototype.split() - 对一个字符串执行,它将它“拆分”为所提供的子字符串的每个实例的数组。即'abc'.split('b'); // ['a','c']
  2. Array.prototype.join() - 在一个数组上执行,它将每个元素与给定的字符串“连接”起来。即['a','c'].join('d'); // 'adc'
  3. 那你怎么用这些呢?简单!

    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('" "') + '"');