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.

1

3 Answers 3

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:

Sign up to request clarification or add additional context in comments.

4 Comments

it ignores all of special chars, for example if you write [asd] then its output asd
Works good. In your DEMO, I have given input as Hello, stackoverflow! It showed length as 3. Shouldn't it be 2?
as i said, it ignores special chars that means count them too
@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
0

You can try this

textAreaContent.split(/\W+/);

Comments

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+/");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.