I have string
var myString = 'Hello word Sentence number';
I need make array like ["Hello ","word ","Sentence ","number "]
with space after words, I did myString.split(/(?= )/);
but I received ["Hello"," word"," Sentence"," number"]
How to make that space was after words?
I get this line during the event "keyup" the space is a sign that the word over and it can be compared. I don't need .trim()
5 Answers 5
A foreach loop to go through each item in the array would work:
`
var myString = 'Hello word Sentence number';
var myStringArray = myString.split(" ");
myStringArray.forEach(function(entry) {
entry += " "
});
`
more on foreach: For-each over an array in JavaScript?
Comments
Not quite what you were after, but you can split on word boundaries using the regex token \b. Here's a fiddle: https://jsfiddle.net/930xy5b7/
myString.split(/\b/);
3 Comments
You can go back after splitting and "manually" add a space to each word, like this:
var myString = 'Hello word Sentence number';
var splitArray = myString.split(" ");
for(var x = 0; x < splitArray.length; x++){
splitArray[x] = splitArray[
}
Comments
If you use jquery, you could use 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 + " ";
});
Or, as suggested, use Array.prototype.map if you're not using jquery:
//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 Comment
Array.prototype.map, and leave jQuery out of this.ES6 map function:
const myString = 'Hello word Sentence number';
const splitString = myString.split(' ').map(el => `${el} `);
console.log(splitString);
splitfunction. Your example is a little unclear because you add a space to the last element,number, even though there's not a space after it in your original string. You can always just loop through the array and manually add a space to each element..trim()that way you don't have to worry about the spaces at all...