js split array添加空间

时间:2015-06-24 18:30:23

标签: javascript split

我有字符串

var myString = 'Hello word Sentence number';

我需要像["Hello ","word ","Sentence ","number "]这样的数组 在单词之后,我做了myString.split(/(?= )/); 但是我收到了["Hello"," word"," Sentence"," number"] 如何使这个空间在言语之后?

我在事件“keyup”期间得到这一行,空格是一个标志,这个词可以比较。我不需要.trim()

5 个答案:

答案 0 :(得分:1)

如果您使用jquery,则可以使用map

//this is what you've done
var myString = 'Hello word Sentence number';
var arr = myString.split(/(?= )/);

//this will add a space in the end of every string of the array
var arrWithSpaces = $.map( arr, function(el){
  return el + " ";
});

或者,根据建议,如果您不使用jquery,请使用Array.prototype.map

//this is what you've done
var myString = 'Hello word Sentence number'; 
var arr = myString.split(/(?= )/);

//this will add a space in the end of every string of the array
var arrWithSpaces = arr.map( function(el){ 
    return el + " "; 
});

答案 1 :(得分:1)

遍历数组中每个项目的foreach循环将起作用:

`

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request === 'What I want to recieve') {
        // Do something
        sendResponse('A response');
    } 
});

`

更多关于foreach:For-each over an array in JavaScript?

答案 2 :(得分:0)

您可以在拆分后返回并“手动”为每个单词添加空格,如下所示:

var myString = 'Hello word Sentence number';
var splitArray = myString.split(" ");

for(var x = 0; x < splitArray.length; x++){
  splitArray[x] = splitArray[
}

答案 3 :(得分:0)

不完全是你所追求的,但你可以使用正则表达式令牌分割字边界\ b。这是一个小提琴:https://jsfiddle.net/930xy5b7/

myString.split(/\b/);

答案 4 :(得分:0)

ES6地图功能:

const myString = 'Hello word Sentence number';
const splitString = myString.split(' ').map(el => `${el} `);
console.log(splitString);