简体   繁体   中英

How to get text that uses special characters in textarea?

Anyone can help me?

I have a textarea, how can I get the special values of the textarea with php and jquery?

If, the input result of the textarea is:

How to create a simple #program with #php for a #beginner.

How can I get characters only: #programming , #php and #beginner

from this form:

<form>
<textarea class="textarea" id="textarea" name="textarea"></textarea>
<input type="submit" value="check">
</form>

Thank you for your help.

You can do some simple string manipulation:

 var x = 'How to create a simple #program with #php for a #beginner.'; var hash = []; x.split(' ').forEach(function(v) {//split the string by space if(v.charAt(0) == '#')//test if the first character is the hash hash.push(v);//append it to the array }); console.log(hash) 

var string = "How to create a simple #program with #php for a #beginner.";
var splitString = string.split(/#*\s/);
var result = [];
for(var i=0;i<splitString.length;i++){
    if(splitString[i].startsWith('#'))
        result.push(splitString[i]);
}
console.log(result);

This should do the trick.

You can use a regular expression like /#[a-z0-9]+/gi to do a case-insensitive global match of any "words" (one or more letters and numbers) that follow a hash character, perhaps using the string .match() method :

 var text = 'How to create a simple #program with #php for a #beginner.'; var tags = text.match(/#[a-z0-9]+/gi); console.log(tags); 

The following binds a submit event listener to the form (I've given your form an ID for ease of selection from JS) to get the current value of the textarea at the time the form is submitted.

 document.getElementById("theForm").addEventListener("submit", function(e) { e.preventDefault(); // for demo purposes cancel the form submission var text = document.getElementById("textarea").value; // get full text var tags = text.match(/#[a-z0-9]+/gi); // match the tags console.log(tags); }); 
 <form id="theForm"> <textarea class="textarea" id="textarea" name="textarea">How to create a simple #program with #php for a #beginner.</textarea> <input type="submit" value="check"> </form> 

Try this

function getSpecialWords(str)
{
    var words = str.split(" ");
    var character = "#";
    var result = [];

    for(var i=0; i<words.length; i++)
    {
        if(words[i].charAt(0) == character)
        {
            result.push(words[i]);
        }
    }

    return result;
}

var str = "How to create a simple #program with #php for a #beginner.";


console.log( getWords(str) );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM