0

I have a textArea. I am trying to split each string from a paragraph, which has proper grammar based punctuation delimiters like ,.!? or more if any.

I am trying to achieve this using Javascript. I am trying to get all such strings in that using the regular expression as in this answer

But here, in javascript for me it's not working. Here's my code snippet for more clarity

$('#split').click(function(){
    var textAreaContent = $('#textArea').val();
    //split the string i.e.., textArea content
    var splittedArray = textAreaContent.split("\\W+");
    alert("Splitted Array is "+splittedArray);
    var lengthOfsplittedArray = splittedArray.length;
    alert('lengthOfText '+lengthOfsplittedArray);
  });

Since its unable to split, its always showing length as 1. What could be the apt regular expression here.

Community
  • 1
  • 1
srk
  • 4,857
  • 12
  • 65
  • 109

3 Answers3

2

The regular expression shouldn't differ between Java and JavaScript, but the .split() method in Java accepts a regular expression string. If you want to use a regular expression in JavaScript, you need to create one...like so:

.split(/\W+/)

DEMO: http://jsfiddle.net/s3B5J/

Notice the / and / to create a regular expression literal. The Java version needed two "\" because it was enclosed in a string.

Reference:

Ian
  • 50,146
  • 13
  • 101
  • 111
  • it ignores all of special chars, for example if you write `[asd]` then its output `asd` – rcpayan May 18 '13 at 14:08
  • Works good. In your DEMO, I have given input as Hello, stackoverflow! It showed length as 3. Shouldn't it be 2? – srk May 18 '13 at 14:11
  • as i said, it ignores special chars that means count them too – rcpayan May 18 '13 at 14:20
  • @srk You asked how to get the regular expression to work in JavaScript - which is what I provided. If you need it to do something specific more, explain. So is your main point to get all **words** in the textarea? Without the sentence punctuation? I'm happy to try and help – Ian May 18 '13 at 14:29
0

You can try this

textAreaContent.split(/\W+/);
Anirudha
  • 32,393
  • 7
  • 68
  • 89
0
\W+ : Matches any character that is not a word character (alphanumeric & underscore).

so it counts except alphanumerics and underscore! if you dont need to split " " (space) then you can use;

var splittedArray = textAreaContent.split("/\n+/");
rcpayan
  • 535
  • 3
  • 15