Get first word of string - javascript

Okay, here is my code with details of what I have tried to do:
var str = "Hello m|sss sss|mmm ss";
//Now I separate them by "|"
var str1 = str.split("|");
//Now I want to get the first word of every split-ed sting parts:
for (var i = 0; i < codelines.length; i++) {
//What to do here to get the first word of every spilt
}
So what should I do there? :\
What I want to get is :
firstword[0] will give "Hello"
firstword[1] will give "sss"
firstword[2] will give "mmm"

Use regular expression
var totalWords = "foo love bar very much.";
var firstWord = totalWords.replace(/ .*/,'');
$('body').append(firstWord);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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

To get first word of string you can do this:
let myStr = "Hello World"
let firstWord = myStr.split(" ")[0]
console.log(firstWord)
split(" ") will convert your string into an array of words (substrings resulted from the division of the string using space as divider) and then you can get the first word accessing the first array element with [0].
See more about the split method.

I 'm using this :
function getFirstWord(str) {
let spaceIndex = str.indexOf(' ');
return spaceIndex === -1 ? str : str.substring(0, spaceIndex);
};

How about using underscorejs
str = "There are so many places on earth that I want to go, i just dont have time. :("
firstWord = _.first( str.split(" ") )

An improvement upon previous answers (working on multi-line or tabbed strings):
String.prototype.firstWord = function(){return this.replace(/\s.*/,'')}
Or using search and substr:
String.prototype.firstWord = function(){let sp=this.search(/\s/);return sp<0?this:this.substr(0,sp)}
Or without regex:
String.prototype.firstWord = function(){
let sps=[this.indexOf(' '),this.indexOf('\u000A'),this.indexOf('\u0009')].
filter((e)=>e!==-1);
return sps.length? this.substr(0,Math.min(...sps)) : this;
}
Examples:
String.prototype.firstWord = function(){return this.replace(/\s.*/,'')}
console.log(`linebreak
example 1`.firstWord()); // -> linebreak
console.log('space example 2'.firstWord()); // -> singleline
console.log('tab example 3'.firstWord()); // -> tab

var str = "Hello m|sss sss|mmm ss"
//Now i separate them by "|"
var str1 = str.split('|');
//Now i want to get the first word of every split-ed sting parts:
for (var i=0;i<str1.length;i++)
{
//What to do here to get the first word :)
var firstWord = str1[i].split(' ')[0];
alert(firstWord);
}

This code should get you the first word,
var str = "Hello m|sss sss|mmm ss"
//Now i separate them by "|"
var str1 = str.split('|');
//Now i want to get the first word of every split-ed sting parts:
for (var i=0;i<str1.length;i++)
{
//What to do here to get the first word :(
var words = str1[i].split(" ");
console.log(words[0]);
}

In modern JS, this is simplified, and you can write something like this:
const firstWords = str =>
str .split (/\|/) .map (s => s .split (/\s+/) [0])
const str = "Hello m|sss sss|mmm ss"
console .log (firstWords (str))
We first split the string on the | and then split each string in the resulting array on any white space, keeping only the first one.

I'm surprised this method hasn't been mentioned: "Some string".split(' ').shift()
To answer the question directly:
let firstWords = []
let str = "Hello m|sss sss|mmm ss";
const codeLines = str.split("|");
for (var i = 0; i < codeLines.length; i++) {
const first = codeLines[i].split(' ').shift()
firstWords.push(first)
}

const getFirstWord = string => {
const firstWord = [];
for (let i = 0; i < string.length; i += 1) {
if (string[i] === ' ') break;
firstWord.push(string[i]);
}
return firstWord.join('');
};
console.log(getFirstWord('Hello World'));
or simplify it:
const getFirstWord = string => {
const words = string.split(' ');
return words[0];
};
console.log(getFirstWord('Hello World'));

This code should get you the first word,
const myName = 'Jahid Bhuiyan';
console.log(myName.slice(0, myName.indexOf(' ')));
Ans will be "Jahid"

Related

use js change var str="are you okay" to are| you| okay|

var str="are you okay"
I want to change this str like this
are| you| okay|
Here is my code
function split() {
var str = "are you okay",
res = ""
var arr = str.trim().split(/\s+/)
for (i = 0; i < arr.length; i++) {
res += arr[i] + "|"
}
return res;
}
so I don't know how to return the result like are| you| okay|
There is a shorter solution. You can first remove double spaces:
var str = "are you okay";
var nospaces = str.replace(/\s+/g,' ').trim();
and then replace spaces with | :
var final_str = nospaces.replace(' ', '| ');
You could use combination of .split() to separate each space, .filter() to return words and .join() to merge them back into one word:
var str="are you okay";
const modifiedstr = `${str.split(/\s+/).filter(e=> e != '').join('| ')}|`;
console.log(modifiedstr);
This produces the desired output:
const split = (str) => str.trim().replace(/\s+/g, '| ') + '|';
If you want to continue that approach all you really need is map with a quick little join on the end:
function split(str) {
return str.trim().split(/\s+/).map(s => `${s}| `).join('').trim();
}
console.log(split("are you okay"));
Note that ES6 makes this pretty easy with template literals and arrow functions.
You could also do this with a simple regular expression if you're inclined:
function split(str) {
return str.replace(/\s+/g, '| ');
}
console.log(split("are you okay"));
Where here the /g flag means "global" as in "replace all instances". By default it will just do the first.
Your code look good you have to just do this:
function split() {
var str = "are you okay",
res = ""
var arr = str.trim().split(/\s+/)
for (i = 0; i < arr.length; i++) {
res += arr[i] + "| "; // add space after | sign
}
return res.trim(); // to remove last space
}
var string = split()
console.log(string)
Or you can do this:
function split(str) {
return str.trim().split(/\s+/).join('| ')+'|';
}
var str = "are you okay";
var result = split(str);
console.log(result)

Is it possible to replace only one character in a string if that character appears twice consecutively?

So I made a method to make the first letter of all the words in any string Uppercase.
String.prototype.toMyCase = function () {
let strArray = Array.from(this.split(" "));
for(let i=0; i<strArray.length; i++){
strArray[i] = strArray[i][0].toUpperCase() + strArray[i].substr(1);
}
let newStr = strArray.toString();
let finalStr = newStr.replace(/,/g, " ");
return finalStr;
};
The problem with this is when I pass a string that has real commas(,) it replace that comma(,) too in the finalStr step. For e.g
console.log("How can mirrors be real, if our eyes aren't real".toMyCase(); gives me
How Can Mirrors Be Real If Our Eyes Aren't Real (there are two spaces after Real).
You can use strArray.join(' ');
String.prototype.toMyCase = function () {
let strArray = Array.from(this.split(" "));
for(let i=0; i<strArray.length; i++){
strArray[i] = strArray[i][0].toUpperCase() + strArray[i].substr(1);
}
return strArray.join(' ');
};
console.log("How can mirrors be real, if our eyes aren't real".toMyCase());
How about with this single line soln after string split(), uppercase first character and join the rest using .map() with the first?,
let str = "How can mirrors be real, if our eyes aren't real";
let captialized_words = str => str.split(' ').map(w => w.substring(0, 1).toUpperCase() + w.substring(1)).join(' ')
console.log(captialized_words(str))
Instead of
let finalStr = newStr.replace(/,/g, " ");
Do
let finalStr = newStr.replace(/,/g, "");

How to split two dimensional array in JavaScript?

I have string like below:
"test[2][1]"
"test[2][2]"
etc
Now, I want to split this string to like this:
split[0] = "test"
split[1] = 2
split[2] = 1
split[0] = "test"
split[1] = 2
split[2] = 2
I tried split in javascript but no success.How can it be possible?
CODE:
string.split('][');
Thanks.
Try this:
.replace(/]/g, '') gets rid of the right square bracket.
.split('[') splits the remaining "test[2[1" into its components.
var str1 = "test[2][1]";
var str2 = "test[2][2]";
var split = str1.replace(/]/g, '').split('[');
var split2 = str2.replace(/]/g, '').split('[');
alert(split);
alert(split2);
you can try :
string.split(/\]?\[|\]\[?/)
function splitter (string) {
var arr = string.split('['),
result = [];
arr.forEach(function (item) {
item = item.replace(/]$/, '');
result.push(item);
})
return result;
}
console.log(splitter("test[2][1]"));
As long as this format is used you can do
var text = "test[1][2]";
var split = text.match(/\w+/g);
But you will run into problems if the three parts contain something else than letters and numbers.
You can split with the [ character and then remove last character from all the elements except the first.
var str = "test[2][2]";
var res = str.split("[");
for(var i=1, len=res.length; i < len; i++) res[i]=res[i].slice(0,-1);
alert(res);

How to get substring value from main string?

I have string similar to this one.
HTML
var str = "samplestring=:customerid and samplestring1=:dept";
JS
var parts = str.split(':');
var answer = parts;
I want to trim substrings which starts with colon: symbol from the main string
But it is returing the value like this
samplestring=,customerid and samplestring1=,dept
But I want it something like this.
customerid,dept
I am getting main string dynamically it may have colon more then 2.
I have created a fiddle also link
var str = "samplestring=:customerid and samplestring1=:dept";
alert(str.match(/:(\w+)/g).map(function(s){return s.substr(1)}).join(","))
you can try regex:
var matches = str.match(/=:(\w+)/g);
var answer = [];
if(matches){
matches.forEach(function(s){
answer.push(s.substr(2));
});
}
Here's a one-liner:
$.map(str.match(/:(\w+)/g), function(e, v) { return e.substr(1); }).join(",")
Try
var str = "samplestring=:customerid and samplestring1=:dept";
var parts = str.split(':');
var dept = parts[2];
var cus_id = parts[1].split(' and ')[0];
alert(cus_id + ", " + dept );
Using this you will get o/p like :customerid,dept
this will give you what you need...
var str = "samplestring=:customerid and samplestring1=:dept";
var parts = str.split(' and ');
var answer = [];
for (var i = 0; i < parts.length; i++) {
answer.push(parts[i].substring(parts[i].indexOf(':')+1));
}
alert(answer);
var str = "samplestring=:customerid and samplestring1=:dept";
alert(str.replace(/[^:]*:(\w+)/g, ",$1").substr(1))
You can try it like this
var str = "samplestring=:customerid and samplestring1=:dept and samplestring11=:dept";
var results = [];
var parts = str.split(' and ');
$.each(parts, function( key, value ) {
results.push(value.split(':')[1]);
});
Now the results array contains the three values customerid, dept, and dept
Here \S where S is capital is to get not space characters so it will get the word till first space match it, so it will match the word after : till the first space and we use /g to not only match the fisrt word and continue search in the string for other matches:
str.match(/:(\S*)/g).map(function(s){return s.substr(1)}).join(",")

Test for multiple words in a string

I have a string like so:
var str = "FacebookExternalHit and some other gibberish";
Now I have a list of strings to test if they exist in str. Here they are in array format:
var bots = ["FacebookExternalHit", "LinkedInBot", "TwitterBot", "Baiduspider"];
What is the fastest and/or shortest method to search str and see if any of the bots values are present? Regex is fine if that's the best method.
Using join you can do:
var m = str.match( new RegExp("\\b(" + bots.join('|') + ")\\b", "ig") );
//=> ["FacebookExternalHit"]
I don't know that regex is necessarily the way to go here. Check out Array.prototype.some()
var str = "FacebookExternalHit and some other gibberish";
var bots = ["FacebookExternalHit", "LinkedInBot", "TwitterBot", "Baiduspider"];
var isBot = bots.some(function(botName) {
return str.indexOf(botName) !== -1;
});
console.log("isBot: %o", isBot);
A regular for loop is even faster:
var str = "FacebookExternalHit and some other gibberish";
var bots = ["FacebookExternalHit", "LinkedInBot", "TwitterBot", "Baiduspider"];
var isBot = false;
for (var i = 0, ln = bots.length; i < ln; i++) {
if (str.indexOf(bots[i]) !== -1) {
isBot = true;
break;
}
}
console.log("isBot: %o", isBot);

Categories

Resources