Home > Back-end >  Javascript Modify First Word
Javascript Modify First Word

Time:06-08

Surely there's a better way of doing this? It's not very elegant. I'm simply wanting to make the first word bolder.

let title_array = title.split(" ");
title_array[0] = "<strong>" title_array[0] "</strong>";
title = title_array.join(" ");

CodePudding user response:

Your approach is good, below is another approach using Regex

var title = "Hello to new StackOverflow";
title = title.replace(/^(\w )/, '<strong>$1</strong>');

console.log(title);

var title = "Hello to new StackOverflow";
title = title.replace(/^(\w )/, '<strong>$1</strong>');

console.log(title);

Since you are using React, you may have to use dangerouslySetInnerHTML to render the html.

So another approach would be something like this in React.

<div>
{
   title.split(" ").map((word, index) => {
     return index === 0 ? <strong>{word}</strong> : ` ${word}`;
  });
}
</div>

CodePudding user response:

I think your current approach is fine. You do have the option of using .replace() also with a regular expression:

const title = "This is a title";
const boldTitle = title.replace(/^[^\s] /, "<strong>$&</strong>");
console.log(boldTitle);
document.body.innerHTML = boldTitle;

Here, the regular expression matches non-whitespace characters ([^\s] ) from the start of the string (^) until it reaches a whitespace character (\s). This match is then used in the replacement (referenced using $&)

CodePudding user response:

I would use a CSS class. Destructuring assignment can help with defining the words, and you can use a template string to return the result.

function embolden(str) {
  const [ first, ...rest ] = str.split(' ');
  return `<span >${first}</span> ${rest.join(' ')}`;
}

const title = 'Javascript Modify First Word';
document.body.innerHTML = embolden(title);
.bold { font-weight: 700; }

CodePudding user response:

For simplicity purposes when coding, please use arrow function combined with RegEx to make it shorter.

const boldFirstWord = strTitle => strTitle.replace(/(^|\.\s)([a-z] )/gi, "$1<strong>$2</strong>");
console.log(boldFirstWord("We simply love JavaScript!!!"));

CodePudding user response:

I think what you have proposed is ok, but I don't think you should use <strong>, maybe this would be a better approach depending on the case:

let title_array = title.split(" ");

title_array[0] = `<span style="font-weight: 700">${title_array[0]}</span>`;
title = `<p>${title_array.join(" ")}</p>`;
  • Related