Insert few characters before character in a string variable (javascript) - javascript

I have this following javascript variable.
var data = "ashley, andy, juana"
i Want the above data to look like this.
var data = "Sports_ashley, Sports_andy, Sports_juana"
It should be dynamic in nature. any number of commas can be present in this variable.
Can someone let me an easy way to achieve this please.

Using .replace should work to add sports before each comma. Below I have included an example.
var data = data.replace(/,/g , ", Sports_");
In that example using RegExp with g flag will replace all commas with Sports, instead of just the first occurrence.
Then at the end you should just be able to append Sports to the end like so.
data = "Sports_" + data;

Probably an overkill, but here is a generic solution
function sportify(data) {
return data
.split(/\s*,\s*/g) //splits the string on any coma and also takes out the surrounding spaces
.map(function(name) { return "Sports_" + name } ) //each name chunk gets "Sport_" prepended to the end
.join(", "); //combine them back together
}
console.log(sportify("ashley, andy, juana"));
console.log(sportify("ashley , andy, juana"));
String.replace()
Array.map()
Array.join()
EDIT: updated with the new version of the OP

Use a regex to replace all occurrences of a , or the beginning of the string using String#replace()
var input = "ashley, andy, juana"
var output = input.replace(/^|,\s*/g, "$&Sports_");
console.log(output);

Related

How to remove special characters from string using javascript

When # comes in string, I want to split it on new line using JavaScript.
Please help me.
Sample input:
This application helps the user to instantiate #Removed#Basic#afdaf#Clip#Python#matching of many parts#
Expected output:
This helps the user to instantiate
Removed
Basic
afdaf
Clip
Python
matching of many parts
you can simply replace '#' by '\n'
var mainVar = 'This application helps the user to instantiate#Removed#Basic#afdaf#Clip#Python#matching';
console.log(mainVar.replace(/[^\w\s]/gi, '\n'));
Convert a string into array and loop through the array and print values one by one.
var str = "helps the user to instantiate #Removed#Basic#afdaf#Clip#Python#matching of many parts#";
str.split("#").forEach(function(entry) {
console.log(entry);
});
You can try this:
You should use the string replace function, with a single regex. Assuming by special characters
var str = "This application helps the user to instantiate #Removed#Basic#afdaf#Clip#Python#matching of many parts#";
console.log(str.replace(/[^a-zA-Z ]/g, "\n"));
The below solution will split based on the # and store it in an array.
This solution will come in handy with splitting strings.
var sentence = '#Removed#Basic#afdaf#Clip#Python#matching of many parts#'
var newSentence = [];
for(var char of sentence.split("#")){
console.log(char); // This will print each string on a new line
newSentence.push(char);
}
console.log(newSentence.join(" "));

Making a javascript function that finds the first word in a string/sentence

I've looked all over the web but couldnt find a good answer to this. I need to write a function that finds the first word in a string/sentence. Its in relation to a html/css/javascript assignment, where i need to color or mark the first word in a long string, containing a story.
I'm thinking a simple for loop could do it, but cant get it to work.
The String global object is a constructor for strings or a sequence of characters.
in javascript String object has methods on his prototype - MDN - String
String.prototype.split() - Reference (MDN)
The split() method splits a String object into an array of strings by separating the string into substrings, using a specified separator string to determine where to make each split.
because you want to split by words, you should split string by "space".
as you can see split method on string return an array, so the first item in array will be the first word.
'Some String Here'.split(' ')[0];
Good Luck!
// Get Results Element
var div = document.querySelector('.results');
// Some string
var someString = 'Hi Hello JavaScript World';
function renderFirstWorkAsMarked(string, color) {
var splitedString = string.split(' ');
var wrapper = document.createElement('div')
var marked = document.createElement('span');
var restString = document.createTextNode(splitedString.slice(1).join(' '))
marked.style.color = color;
marked.innerHTML = `${splitedString[0]} `;
wrapper.appendChild(marked)
wrapper.appendChild(restString)
return wrapper
}
// append on screen
div.append(renderFirstWorkAsMarked(someString, 'red'))
// This is example code for your full question.
<div class="results"></div>
This will do the trick. It splits the string by the whitespace and then provides you the first word using the index.
"Plane Jane Mane".split(" ")[0]
Here's an example, the first console log will show you the formed array, and the second will select the first word in the array:
var word = "Plane Jane Mane"
console.log(word.split(" "))
console.log(word.split(" ")[0])
I answer your question with ES6 arrow function. see below code:
const firstWord = string => string.split(' ')[0];
Or you can use regex but I prefer the first function:
const firstWord = string => string.match(/^[\w\d]+/gs)[0];
let string = 'This is a sentence';
let word = string.split(' ')[0];
console.log(word);
Firstly, split sentences. Secondly, Split words and take first:
yourtext
.split(/(?<!\w\.\w.)(?<![A-Z][a-z]\.)(?<=\.|\?)\s/g)
.map(w => w.split(/((\b[^\s]+\b)((?<=\.\w).)?)/g)[1])
Example
I've looked all over the web but couldnt find a good answer to this. I need to write a function that finds the first word in a string/sentence. Its in relation to a html/css/javascript assignment, where i need to color or mark the first word in a long string, containing a story.
I'm thinking a simple for loop could do it, but cant get it to work.
Result
I've,I,Its,I'm

How to convert an array like string to array in node.js?

Actually I'm getting the arraylist from android device in node.js . But as it's in string form so I wanna convert it into an array . For that I've referred a lot of similar questions in SO but none of them were helpful . I also tried to use JSON.parse() but it was not helpful.
I'm getting societyList in form '[Art, Photography, Writing]'.Thus how to convert this format to an array?
Code:
var soc_arr=JSON.parse(data.societyList)
console.log(soc_arr.length)
use something like this
var array = arrayList.replace(/^\[|\]$/g, "").split(", ");
UPDATE:
After #drinchev suggestion regex used.
regex matches char starts with '[' and ends with ']'
This string is not valid JSON since it does not use the "" to indicate a string.
The best way would be to parse it yourself using a method like below:
let data = '[test1, test2, test3]';
let parts = data
.trim() // trim the initial data!
.substr(1,data.length-2) // remove the brackets from string
.split(',') // plit the string using the seperator ','
.map(e=>e.trim()) // trim the results to remove spaces at start and end
console.log(parts);
RegExp.match() maybe
console.log('[Art, Photography, Writing]'.match(/\w+/g))
So match() applies on any string and will split it into array elements.
Use replace and split. In addition, use trim() to remove the trailing and leading whitespaces from the array element.
var str = '[Art, Photography, Writing]';
var JSONData = str.replace('[','').replace(']','').split(',').map(x => x.trim());
console.log(JSONData);

Parse string regex for known keys but leave separator

Ok, So I hit a little bit of a snag trying to make a regex.
Essentially, I want a string like:
error=some=new item user=max dateFrom=2013-01-15T05:00:00.000Z dateTo=2013-01-16T05:00:00.000Z
to be parsed to read
error=some=new item
user=max
dateFrom=2013-01-15T05:00:00.000Z
ateTo=2013-01-16T05:00:00.000Z
So I want it to pull known keywords, and ignore other strings that have =.
My current regex looks like this:
(error|user|dateFrom|dateTo|timeFrom|timeTo|hang)\=[\w\s\f\-\:]+(?![(error|user|dateFrom|dateTo|timeFrom|timeTo|hang)\=])
So I'm using known keywords to be used dynamically so I can list them as being know.
How could I write it to include this requirement?
You could use a replace like so:
var input = "error=some=new item user=max dateFrom=2013-01-15T05:00:00.000Z dateTo=2013-01-16T05:00:00.000Z";
var result = input.replace(/\s*\b((?:error|user|dateFrom|dateTo|timeFrom|timeTo|hang)=)/g, "\n$1");
result = result.replace(/^\r?\n/, ""); // remove the first line
Result:
error=some=new item
user=max
dateFrom=2013-01-15T05:00:00.000Z
dateTo=2013-01-16T05:00:00.000Z
Another way to tokenize the string:
var tokens = inputString.split(/ (?=[^= ]+=)/);
The regex looks for space that is succeeded by (a non-space-non-equal-sign sequence that ends with a =), and split at those spaces.
Result:
["error=some=new item", "user=max", "dateFrom=2013-01-15T05:00:00.000Z", "dateTo=2013-01-16T05:00:00.000Z"]
Using the technique above and adapt your regex from your question:
var tokens = inputString.split(/(?=\b(?:error|user|dateFrom|dateTo|timeFrom|timeTo|hang)=)/);
This will correctly split the input pointed out by Qtax mentioned in the comment: "error=user=max foo=bar"
["error=", "user=max foo=bar"]

jQuery return first 5 words of a string without commas

I'm trying to return the first 5 words of a string in a readable format, no "" or commas separating words. I'm not sure if its a regex thing or what, but I can't figure it out although its probably simple. Thanks!
See what I have thus far:
http://jsfiddle.net/ccnokes/GktTd/
This is the function I'm using:
function getWords(string){
var words = string.split(/\s+/).slice(1,5);
return words;
}
The only thing you are missing is a join()
Try this:
function getWords(str) {
return str.split(/\s+/).slice(0,5).join(" ");
}
This will do something like:
var str = "This is a long string with more than 5 words.";
console.log(getWords(str)); // << outputs "This is a long string"
Take a look at this link for a further explanation of the .join(). function in javascript. Essentially - if you don't supply an argument, it uses the default delimiter ,, whereas if you supply one (as I'm doing in the above example, by providing " " - it will use that instead. This is why the output becomes the first 5 words, separated by a space between each.
Those commas are coming from how you output the data:
//write to DOM
$('<h2 />').text(getWords(str).join(' ')).appendTo('body');
​
When you add a string to getWords(str), javascript tries to convert the array into a string - it does this by joining the words with commas. If you want to join them with something else, use join.
Troy Alford solution is working, but is has one drawback. If between words there will be more than one space, or new line character (\n) it will be converted to single space, e.g:
'jQuery is a
multi-browser'
will be converted to
'jQuery is a multi-browser'
To fix this issue, we might use word boundary regex. It might looks like this:
function getFirstWords(text, wordsAmount) {
const arr = text.split(/\b/g);
const arrItemsAmount = (/\b/.exec(text) && /\b/.exec(text).index) ?
wordsAmount * 2 :
wordsAmount * 2 - 1;
return arr.slice(0, arrItemsAmount).join('');
}
You can do it with str.substring(1,15)

Categories