From this string:
$input = "Some terms with spaces between";
how can I produce this array?
$output = ['Some', 'terms', 'with', 'spaces', 'between'];
Don’t Panic
40.9k10 gold badges62 silver badges79 bronze badges
asked Mar 6, 2009 at 12:43
You could use explode
, split
or preg_split
.
explode
uses a fixed string:
$parts = explode(' ', $string);
while split
and preg_split
use a regular expression:
$parts = split(' +', $string);
$parts = preg_split('/ +/', $string);
An example where the regular expression based splitting is useful:
$string = 'foo bar'; // multiple spaces
var_dump(explode(' ', $string));
var_dump(split(' +', $string));
var_dump(preg_split('/ +/', $string));
answered Mar 6, 2009 at 12:46
GumboGumbo
638k108 gold badges773 silver badges841 bronze badges
1
$parts = explode(" ", $str);
answered Mar 6, 2009 at 12:46
Can Berk GüderCan Berk Güder
109k25 gold badges129 silver badges137 bronze badges
print_r(str_word_count("this is a sentence", 1));
Results in:
Array ( [0] => this [1] => is [2] => a [3] => sentence )
answered Jul 4, 2010 at 15:53
TheMagicianTheMagician
1,8467 gold badges20 silver badges26 bronze badges
Just thought that it’d be worth mentioning that the regular expression Gumbo posted—although it will more than likely suffice for most—may not catch all cases of white-space. An example: Using the regular expression in the approved answer on the string below:
$sentence = "Hello my name is peter string splitter";
Provided me with the following output through print_r:
Array
(
[0] => Hello
[1] => my
[2] => name
[3] => is
[4] => peter
[5] => string
[6] => splitter
)
Where as, when using the following regular expression:
preg_split('/s+/', $sentence);
Provided me with the following (desired) output:
Array
(
[0] => Hello
[1] => my
[2] => name
[3] => is
[4] => peter
[5] => string
[6] => splitter
)
Hope it helps anyone stuck at a similar hurdle and is confused as to why.
answered Jan 15, 2015 at 9:24
HughHugh
1831 gold badge1 silver badge11 bronze badges
Just a question, but are you trying to make json out of the data? If so, then you might consider something like this:
return json_encode(explode(' ', $inputString));
answered Mar 6, 2009 at 16:36
Cory CollierCory Collier
8741 gold badge10 silver badges20 bronze badges
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function byteArrayToWordArray(ba) { | |
var wa = [], | |
i; | |
for (i = 0; i < ba.length; i++) { | |
wa[(i / 4) | 0] |= ba[i] << (24 — 8 * i); | |
} | |
return CryptoJS.lib.WordArray.create(wa, ba.length); | |
} | |
function wordToByteArray(word, length) { | |
var ba = [], | |
i, | |
xFF = 0xFF; | |
if (length > 0) | |
ba.push(word >>> 24); | |
if (length > 1) | |
ba.push((word >>> 16) & xFF); | |
if (length > 2) | |
ba.push((word >>> 8) & xFF); | |
if (length > 3) | |
ba.push(word & xFF); | |
return ba; | |
} | |
function wordArrayToByteArray(wordArray, length) { | |
if (wordArray.hasOwnProperty(«sigBytes») && wordArray.hasOwnProperty(«words»)) { | |
length = wordArray.sigBytes; | |
wordArray = wordArray.words; | |
} | |
var result = [], | |
bytes, | |
i = 0; | |
while (length > 0) { | |
bytes = wordToByteArray(wordArray[i], Math.min(4, length)); | |
length -= bytes.length; | |
result.push(bytes); | |
i++; | |
} | |
return [].concat.apply([], result); | |
} |
Last update on November 02 2022 12:27:58 (UTC/GMT +8 hours)
JavaScript String: Exercise-3 with Solution
Write a JavaScript function to split a string and convert it into an array of words.
Test Data :
console.log(string_to_array(«Robin Singh»));
[«Robin», «Singh»]
Pictorial Presentation:
Sample Solution:-
HTML Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Split a string and convert it into an array of words.</title>
</head>
<body>
</body>
</html>
JavaScript Code:
string_to_array = function (str) {
return str.trim().split(" ");
};
console.log(string_to_array("Robin Singh"));
Sample Output:
["Robin","Singh"]
Flowchart:
Live Demo:
See the Pen JavaScript Split a string and convert it into an array of words — string-ex-3 by w3resource (@w3resource) on CodePen.
Contribute your code and comments through Disqus.
Previous: Write a JavaScript function to check whether a string is blank or not.
Next: Write a JavaScript function to extract a specified number of characters from a string.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource’s quiz.
JavaScript: Tips of the Day
Returns every element that exists in any of the two arrays once, using a provided comparator function
Example:
const tips_unionWith = (a, b, comp) => Array.from(new Set([...a, ...b.filter(x => a.findIndex(y => comp(x, y)) === -1)])); ? console.log(tips_unionWith([1, 2.5, 3.5, 4, 0], [4.5, 3, 0, 3.9], (a, b) => Math.round(a) === Math.round(b)));
Output:
[1,2.5,3.5,4,0,4.5]
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises
Here are 4 ways to split a word into an array of characters. «Split» is the most common and more robust way. But with the addition of ES6, there are more tools in the JS arsenal to play with 🧰
I always like to see all the possible ways to solve something because then you can choose the best way for your use case. Also, when you see it pop up in someone’s codebase, you will understand it with ease 👍
- Scenarios
- Array of Characters
- Specific Separators
- Strings containing Emojis
- A caveat about Object.assign ⚠️
- Community Input
- Resources
# Scenarios
Instead of going through the pros and cons of each different way. Let me show you the different scenarios where one is preferred over the other.
# Array of Characters
If all you’re doing is wanting separate the string by each string character, all of the ways are good and will give you the same result
# Specific Separators
If you want to split your string by a specific character, then split
is the way to go.
The other ways are limited by each string character only
# Strings containing Emojis
If your strings contain emojis, then split
or Object.assign
might not be the best choice. Let’s see what happens:
However, if we use the other ways, it works :
This is because split
separates characters by UTF-16 code units which are problematic because emoji characters are UTF-8. If we look at our yum emoji '😋'
it’s actually made up of 2 characters NOT 1 as we perceive.
This is what’s called grapheme clusters — where the user perceives it as 1 single unit, but under the hood, it’s in fact made up of multiple units. The newer methods spread
and Array.from
are better equipped to handle these and will split your string by grapheme clusters 👍
# A caveat about Object.assign
⚠️
One thing to note Object.assign
is that it doesn’t actually produce a pure array. Let’s start with its definition
The Object.assign() method copies all enumerable own properties from one or more source objects to a target object
The key there is «copies all enumerable own properties». So what we’re doing here Object.assign([], string)
it copying ALL of our string properties over to our new array. Which means we have an Array PLUS some string methods.
# TypeScript Test: Result array is not a string[]
type 😱
This is more evident if we use the TypeScript Playground. Feel free to copy the code and paste in the playground, where you can hover on the variable to view the types. Since this is just an article, I’ll paste the result here so you can follow along.
However, if we look at the result type of Object.assign
. It doesn’t give us an Array of strings.
# TypeScript Test: Result array can access string properties 😱
We can do further check this by accessing a property that should only be available to a String
.
So that means if I call bold
on our Array, it should tell us this property doesn’t exist. This is what we expect to see:
BUT, if we call bold
on our supposedly Array created by Object.assign
, it works 😱
☝️ And this is because Object.assign
copies over ALL the properties over from the original String. Here’s how I’d explain it in non-dev terms. You go to a store to buy a dog. But then store Object.assign
sells you a dog that has dragon wings. This sounds super cool, but this isn’t really a rental friendly pet. Hmm…I don’t think this is my best example. But I think you get my point 😂
# Conversion seems okay in browser 🙂
Now I don’t think this is a major deal-breaker, cause:
It seems that browsers have some kind of mechanism in place to «safely» do Object.assign([], «string») and avoid adding the methods of that string to the array.
Thank you @lukeshiru: for sharing this knowledge for me 👏 He also created a TypeScript playground code so you can see > link
@CaptainOrion_: Turn string into char Array but using map function 🤣
@HiUmesh2: Array.prototype.slice.call('string')
wil do the trick too
@inside.code: Extra info: it’s safer to use the spread operator (second method) rather than String.prototype.split('')
(first method), because split()
doesn’t work with some uncommon characters.
@faerberrr: I had a string that contained special characters like åæāă
etc. When I split them using the .split('')
method and ran .length
, it returned twice the expected value! Switching to the spread operator fixed the problem.
# Resources
- MDN Web Docs: split
- MDN Web Docs: spread
- MDN Web Docs: Array.from
- MDN Web Docs: Object.assign
- Stack Overflow: How do I split a string, breaking at a particular character?
- Stack Overflow: How do you get a string to a character array in JavaScript?
- Stack Overflow: How do I split a string into an array of characters?
- Stack Overflow: Convert utf-8 to Unicode to find emoji in string in java
Hi! I’ve taken my first steps into the world of c++ by trying to write a
text adventure game. Things are proceeding fine, but there’s some code
in there that isn’t very well coded. More specifically, I use the
following code:
…
string word [4];
size_t pos = action.find(» «);
word[0] = action.substr (0,pos);
if (pos < action.size() — 2)
{
word[1] = action.substr(pos + 1);
}
string word1 [2];
for (int i=1;i<3;i++)
{
pos = word[i].find(» «);
if (pos == string::npos) goto skippy;
word1[i-1] = word[i].substr (0,pos);
if (pos < word[i].size() — 2)
{
word[i+1] = word[i].substr(pos + 1);
}
word[i] = word1[i-1];
}
skippy:
…
To convert a string called ‘action’ into the array word[4]. Is there a
way to do this more efficiently?
Thanks
Apr 19 ’07
#1