Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add square bracket in first and last word of a sentence (multiple sentence) in Javascript

I will input few sentences and the output will be wrap up every sentence with square bracket.I have tried so far:

  $('.addCharacter').click(function(event) {
    var textareaInput=$('.textareaInput').val();
    var myString = '[' + textareaInput + ']';
    console.log(myString);
  });

Input:

demo text one  
demo text two  
demo text three

Output:

[demo text one
demo text two
demo text three]

But I want output should be:

[demo text one]
[demo text two]
[demo text three]

I think it can be done with regex.I am not so good in regex.Could anyone one tell me the way?

like image 268
Chonchol Mahmud Avatar asked Jan 30 '26 21:01

Chonchol Mahmud


2 Answers

Replace this line

 var myString = '[' + textareaInput + ']';

with

 var myString = '[' + textareaInput.split("\n").join("]\n[") + ']';

If you are getting an extra space then use this regex (/\s*\n\s*/) for splitting

 var myString = '[' + textareaInput.split(/\s*\n\s*/).join("]\n[") + ']';
like image 139
gurvinder372 Avatar answered Feb 02 '26 11:02

gurvinder372


Use replace() with regex having m(multiline) modifier

multiline; treat beginning and end characters (^ and $) as working over multiple lines (i.e., match the beginning or end of each line (delimited by \n or \r), not only the very beginning or end of the whole input string) (Taken from here )

var textareaInput = `demo text one  
demo text two 
demo text three`;

var myString = textareaInput.replace(/^[^\S\r\n]*(.*?)[^\S\r\n]*$/gm, '[$1]');

console.log(myString);


UPDATE : Updated the regex to match white spaces(which is not newline) in at the beginning and ending. ( as in @WiktorStribiżew answer )

Regex explanation here

Regular expression visualization


Or use replace() with callback and apply trim()

var textareaInput = `demo text one  
demo text two 
demo text three`;

var myString = textareaInput.replace(/^.*$/gm, function(m) {
  return '[' + m.trim() + ']'
});

console.log(myString);

Using split() and join() can be do the job that approach is also added here, instead of join() using reduce() you can do something like this for fun :)

var textareaInput = `demo text one  
demo text two 
demo text three`;

var myString = textareaInput.split(/\n/).reduce(function(a, b) {
  return (a.length ? a + '\n' : '') + '[' + b.trim() + ']'
}, '')

console.log(myString);
like image 43
Pranav C Balan Avatar answered Feb 02 '26 10:02

Pranav C Balan