Javascript,逗号和句号中的正则表达式

时间:2015-12-03 18:21:07

标签: javascript regex

我正在为我的朋友做一个忙(她想要一个带有文本转换器的网站),我遇到了一个问题。对于我必须工作的代码,它需要按空格分割句子,但也要保留逗号和句点。

EX:

输入:["Hello", ",", "my", "name", "is", "Jack", "."]

创建的数组:function tick() { world.step(timeStep); drawScene(); if(cubeBody.velocity.norm() < 0.001) { var direction = cubeBody.quaternion.toAxisAngle()[0]; console.log(direction); if (direction.x < 0.1 && direction.x > -0.1 && direction.y < 0.1 && direction.y > -0.1) { console.log("side 1 or 6"); } else if (direction.y > 0.1 && direction.z < 0.1 && direction.z > -0.1) { console.log("side 2"); } else if (direction.y < -0.1 && direction.z < 0.1 && direction.z > -0.1) { console.log("side 5"); } else if (direction.x > 0.1 && direction.z < 0.1 && direction.z > -0.1) { console.log("side 3"); } else if (direction.x > 0.1 && direction.z < 0.1 && direction.z > -0.1) { console.log("side 4"); } else { console.log("we got trouble"); } } else { requestAnimationFrame(tick); } }

我认为这需要正则表达式才能完成。我试图在JavaScript中执行此操作,我将不胜感激任何帮助。

4 个答案:

答案 0 :(得分:1)

避免使用正则表达式的快速而肮脏的解决方案:

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

答案 1 :(得分:0)

试试这个

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);
});

不是正则表达式,但也许可以帮助你。

jsfiddler

答案 2 :(得分:0)

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

由此分开。参见演示。

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

答案 3 :(得分:0)

我的正则表达不是很好,所以在这个例子中我也必须使用filter

var removeSpaces = function (el) { return el !== ' '; }
var out = str.split(/\b/g).filter(removeSpaces);

// [ "Hello", ", ", "my", "name", "is", "Jack", "." ]

DEMO