最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - Add square bracket in first and last word of a sentence (multiple sentence) in Javascript - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question edited May 24, 2016 at 10:20 Pranav C Balan 115k25 gold badges171 silver badges195 bronze badges asked May 24, 2016 at 10:11 Chonchol MahmudChonchol Mahmud 2,7358 gold badges41 silver badges77 bronze badges 1
  • 2 this – rock321987 Commented May 24, 2016 at 10:13
Add a ment  | 

4 Answers 4

Reset to default 5

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[") + ']';

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


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

A non-regex way:

var textareaInput = `demo text one  
    demo text two  


    demo text three   `;
var res = '[' + textareaInput.split("\n").map(x => x.trim()).join("]\n[") + ']';
document.body.innerHTML = "<pre>" + res + "</pre>";

You can use a regex approach, too:

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

The ^[^\S\r\n]*(.*?)[^\S\r\n]*$ pattern will match any line (due to the /m modifier that makes ^ match the line start and $ match the line end), even an empty one (due to the * quantifier that matches zero or more occurrences), and replace with a [, the line up to the last whitespace(s), and a ] ($1 is a backreference to the Group 1 value).

Details:

  • ^ - line start
  • [^\S\r\n]* - zero or more horizontal whitespaces (not removing empty lines)
  • (.*?) - any characters but a newline, as few as possible, up to the first
  • [^\S\r\n]* - zero or more whitespaces
  • $ - end of line

See the regex demo

var re = /^[^\S\r\n]*(.*?)[^\S\r\n]*$/gm; 
var str = `demo text one  
demo text two  
demo text three`;
var result = str.replace(re, '[$1]');
document.body.innerHTML = "<pre>" + result + "</pre>";

You can use split method instead of RegEx:

$('.addCharacter').click(function(event) {
    var textareaInput=$('.textareaInput').val().split('\n');
    var output = '';
    $(textareaInput).each( function() {
      output += '[' + this + ']\n';
    });
    console.log(output);
});

In this case it will create an Array of all newlines and you will be able to concat each new line your way.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论