Reputation: 21
I was doing a favor for my friend (she wanted a website with a text converter), and I encountered a problem. For the code I have to work, it needs to split sentences by spaces, but also keep commas and periods.
EX:
Input: "Hello, my name is Jack."
Array Created: ["Hello", ",", "my", "name", "is", "Jack", "."]
I assume this will require regex in order to accomplish. I am attempting to do this in JavaScript, and I would appreciate any help.
Upvotes: 2
Views: 57
Reputation: 108
Quick and dirty solution that avoids regex:
var str = "Hello, my name is Jack.";
//Use .replace() to place a space before each comma and period.
str = str.replace(",", " ,");
str = str.replace(".", " .");
//Use .split() with a whitespace to create your array
var stringArray = str.split(" ");
Upvotes: 1
Reputation: 63587
My regex isn't brilliant so I've had to use filter
too in this example:
var removeSpaces = function (el) { return el !== ' '; }
var out = str.split(/\b/g).filter(removeSpaces);
// [ "Hello", ", ", "my", "name", "is", "Jack", "." ]
Upvotes: 0
Reputation: 67998
([^\s\w])|\s+
Split by this.See demo.
https://regex101.com/r/hE4jH0/33
Upvotes: 0
Reputation: 506
try this
var myString = "Hello, my name is Jack.";
$(document).ready(function(){
var arrSplit = myString.split(' ');
var transform = "";
for(v in arrSplit){
transform += "'" + arrSplit[v].replace(',','').replace('.','') + "',";
if(arrSplit[v].indexOf(',')>0){
transform += "',', ";
}
if(arrSplit[v].indexOf('.')>0){
transform += "'.', ";
}
}
$('#output').html(transform);
});
Is not a regex, but maybe help you.
Upvotes: 0