JackBlack
JackBlack

Reputation: 21

Regular Expressions in Javascript, Commas and Periods

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

Answers (4)

Queequeg
Queequeg

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

DEMO

Upvotes: 1

Andy
Andy

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", "." ]

DEMO

Upvotes: 0

vks
vks

Reputation: 67998

([^\s\w])|\s+

Split by this.See demo.

https://regex101.com/r/hE4jH0/33

Upvotes: 0

RBoschini
RBoschini

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.

jsfiddler

Upvotes: 0

Related Questions