-1

I am a beginner. I was working on a code to make the first word in every <p> sentence bold. So I found a solution which said the regex /(^\w+)/ matches with every first word of the sentence.

What I don't understand is why? I clearly understand what ^ and \w mean. I sort of understand what + means.

I don't understand why all of that together: /(^\w+)/ means the first word of a sentence.

mayersdesign
  • 5,062
  • 4
  • 35
  • 47

2 Answers2

0

/\w/g would return all single characters of the strings.

The regex /\w+/g would return all the words present in your input string as you included a + in your regex. If you add a ^ before that --> /^\w+/g , it identifies the first match word from the beginning of the string.

Hope my explanation is clear. Let me know if you need more info. You can try all these three separately to get more clarity.

Gowtham Shiva
  • 3,802
  • 2
  • 11
  • 27
0

Because that's what you've typed x) !

Here's the details of your expression :

/ RegExp start

( beginning of an expression group

^ beginning of a string marker

\w a word character (equivalent of [a-zA-Z0-9])

+ quantifier, meaning 1 <= amount < +inf of what's right before (here a word character)

) end of an expression group

/RegExp end

Therefore it matches, from the beginning of a string, any amount(from 1 to +inf) of word-characters and ends capture/match when it encounters another character(not word). You might have an end of string at the end of your sentences because it only matches the first word of each string on my end (even when there's punctuation).

If you want to make every <p>'s first word bold try this (not optimized for details and understanding sakes):

function boldifyFirstWordOfP(){
  var $p_arr = $("p");//cache all P
  var p_content_arr;

  $p_arr.each(function(index, elem){
    p_content_arr[index] = $(this).html();//get all innerHTML content
  });

  for(var i=0 ; i < p_content_arr.length ; i++){
    p_content_arr[i] = p_content_arr[i].replace(/(\w+)/g,"<b>$1</b>");//make first word bold
  }

  $p_arr.each(function(index, elem){
    $(this).html( p_content_arr[index] );
  });
}
Vivick
  • 3,434
  • 2
  • 12
  • 25
  • Thanks a lot for that explanation. I found a simpler code though, for making the first word of every

    statement bold. What do you think of this? $("p").each(function() { var change = $(this); change.html(change.text().replace(/(^\w+)/,"$1") ); });

    – Robin Varghese Apr 08 '17 at 20:12