Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript splitting the sentence to each word but do not forget about special characters

Tags:

javascript

Well, I need to split the the sentence into words and manipulate them. My problems is just the words that join with the special characters like me, or do?. I need that two words filtered without , or ? or any special characters. However, I need to join back the manipulated words with the special characters as input.

Anyone can help me? Snippet code so far the sample for my question.

var sentence = "Tell me, what should I do?";

var myApp = angular.module('myApp',[]);
myApp.controller('myCtrl',function($scope){
  
  $scope.output = sentence.split(" ");
  $scope.join_back = $scope.output.join(" ");
  
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp">
  <div ng-controller="myCtrl">
    {{output}}
    <hr/>
    {{join_back}}
  </div>
</div>
like image 288
Nere Avatar asked Feb 03 '26 11:02

Nere


1 Answers

Try this regex to split your string.

sentence.split(/\s|(?=\W)/)

and to remove the space before punctuation use

$scope.output.join(" ").replace(/\s+(\W)/g, "$1");

var sentence = "Tell me, what should I do?";

var myApp = angular.module('myApp',[]);
myApp.controller('myCtrl',function($scope){
  
  $scope.output = sentence.split(/\s|(?=\W)/);
  $scope.join_back = $scope.output.join(" ").replace(/\s+(\W)/g, "$1");
  
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp">
  <div ng-controller="myCtrl">
    {{output}}
    <hr/>
    {{join_back}}
  </div>
</div>
like image 64
Deep Avatar answered Feb 06 '26 00:02

Deep