在JavaScript中添加给定句子的每个单词+面前

时间:2016-05-24 08:05:44

标签: javascript regex

我认为这个问题可以用正则表达式完成。但不幸的是,我在正则表达方面并不擅长。我现在有一句话我想添加' +'在每一个字面前。

示例:输入:我有一支笔 输出将是: + I +有+ a +笔

我找到了一些解决方案,但这些解决方案并不能解决我的问题。我尝试过以下方式。但它给了我这样的输出: I+have+a+pen+但我想要+I +have +a +pen

  $('.addCharacter').click(function(event) {
      var textareaInput=$('.textareaInput').val();
      var strToArr=textareaInput.split(' ');
      var arrUniqueVal=arrUnique(strToArr);

      $('.textareaInput').val(arrUniqueVal.join('+'));
      console.log(arrUniqueVal);
      //alert("ok");
   });

N.B:我希望能够输入多个句子。

更新:输入:

hello world one  
hello world two  
hello world three 

输出:

+hello +world +one  
+hello +world +two  
+hello +world +three 

2 个答案:

答案 0 :(得分:2)

您可以使用此正则表达式:/(^|\s+)/g,它表示匹配字符串的开头(^)或(|)一系列空格字符({{1 }})。围绕它的\s+使其成为捕获组。然后,您将()与替换字符串replace一起使用:"$1+"表示"将捕获组的内容放在此处" $1是一个文字+字符。正则表达式上的+表示"全局" (例如,在整个字符串中):



g




使用var str = "I have a pen"; str = str.replace(/(^|\s+)/g, "$1+"); console.log(str);(空白)的好处是你不必担心一个"字符"是的,所以它甚至在具有不同"字符的语言中也能很好地运行。比JavaScript定义的英文。例如,挪威语:



\s




答案 1 :(得分:-1)

query = Post
  .joins("left join posts p on p.user_id = posts.user_id and p.id > posts.id")
  .where("p.id is null")      
  .includes(:likes).includes(:comments)
  .where(user_id: followings)
  .where(silently_deleted: false)
  .order(user_id: :desc, created_at: :desc)

以上正则表达式将匹配单词的开头并添加“+”。

相关问题