Making a JavaScript Function That Finds the First Word in a String/Sentence

Get first word of string

Split again by a whitespace:

var firstWords = [];
for (var i=0;i<codelines.length;i++)
{
var words = codelines[i].split(" ");
firstWords.push(words[0]);
}

Or use String.prototype.substr() (probably faster):

var firstWords = [];
for (var i=0;i<codelines.length;i++)
{
var codeLine = codelines[i];
var firstWord = codeLine.substr(0, codeLine.indexOf(" "));
  firstWords.push(firstWord);
}

How To Get First Word In The String

JS Fiddle

var str = ["bob, b", "the, d", "builder, e", "can", "he", "fix", "it" ];
for(var i=0; i < str.length; ++i){
console.log(str[i].match('[a-zA-Z]+'));
}

Extract the first word after a given string in a variable

There's no need for a lookahead.

let s = "the description is about fast cars"let f = "description is";
let r = new RegExp(f + "\\s(\\w+)");console.log(s.match(r)[1]);

Get first letter of each word in a string, in JavaScript

I think what you're looking for is the acronym of a supplied string.

var str = "Java Script Object Notation";var matches = str.match(/\b(\w)/g); // ['J','S','O','N']var acronym = matches.join(''); // JSON
console.log(acronym)

JavaScript is taking only the first word in a sentence

You're missing escaped double quotes around the value attribute:

value="+str+"

should be:

value=\""+str+"\"

Fiddle - works now

Explanation of why it was displaying "this"

This means your input tag is effectively composing to this:

<input type="text" ... value=this is the content am fetching>
  • value = "this"
  • is, the, content, am, fetching = attributes without any value

How to create a text component where first word of sentence to be bold?

You could make use of first space char index and .substring

export const Text: React.FunctionComponent<TextProps> = ({
children = ""
}: TextProps) => {
const firstSpaceIndex = children.indexOf(" ");
return (
<>
<span style={{ fontWeight: "bold" }}>
{children.substring(0, firstSpaceIndex)}
</span>
<span>{children.substring(firstSpaceIndex)}</span>
</>
);
};

Edit text-component (forked)



Related Topics



Leave a reply



Submit