change words at particular location in javascript string [duplicate] - javascript

This question already has answers here:
How do I replace a character at a particular index in JavaScript?
(30 answers)
Closed last year.
var str = "Hello world";
str.charAt(2)="P"//instead of l i am assigning the value P
console.log(str)
I want to replace some Text from the string by checking some coditions but i am getting error i also tried replace function but that return nothing does no changes in the string

You need to make an array out of the string to replace by index.
The following should do the trick.
const changeChar = (str, newValue, index) => {
let splitted = str.split("");
splitted[index] = newValue;
return splitted.join("");
}

In JavaScript, strings are immutable, there are 2 ways you can do this which I have mentioned below
1 way can be to split the string using two substrings and stuff the character between them
var s = "Hello world";
var index = 2;
s = s.substring(0, index) + 'p' + s.substring(index + 1);
console.log(s)
2 way can be to convert the string to character array, replace one array member and join it
var str="Hello World"
str = str.split('');
str[2] = 'p';
str = str.join('');
console.log(str)

Related

How can I put the <br> tag in a long string after every 5 words? [duplicate]

This question already has answers here:
How can I break up a javascript string with a new line every five words?
(4 answers)
Closed 3 years ago.
Example:
let str = "Hello this is a test string to figure out how is it possible to split a long string into multiple string";
I want to put the <br> tag after every 5 words like so:
let str1 = "Hello this is a test<br>string to figure out how<br>is it possible to split<br>a long string into multiple<br>string";
How can I do this?
You can split the string on spaces, map the elements of resulting Array to either words preceded by space or every 6th word by <br> and join the result back to a String. Something like:
const str2Split = "Hello this is a test string to figure out how is it possible to split a long string into multiple string";
const withAddedBreaks = str2Split.split(" ")
.map( (v, i) => `${i && i % 5 == 0 ? "<br>" : " "}${v}`);
// ^ insert <br> after every 5 words, otherwise a space
console.log(withAddedBreaks.join("").trim());
// ^ remove first space
console.log(`use method: replace every 4rd space with " !#! "\n${
replaceEveryNthSpace(str2Split, 3, " !#! ")}`);
// a method for it
function replaceEveryNthSpace(str, n, substr) {
return str
.split(" ")
.map( (v, i) => `${i && i % n == 0 ? substr : " "}${v}`)
.join("")
.trim();
}
You've got a bunch of working answers with different approaches but none that uses RegExp so here I'll contribute with one that does:
str1 = str.match(/([^ ]+ +){5}|.+/g).join('<br>');
([^ ]+ +) matches non-spaces (i.e. words) followed by spaces. {5} means it has to match this five times in a row, giving us the match of five words with spaces in between. |.+ is to include anything that remains of the string after the last five word match. The g flag is needed because without it, it would only match a single occurrence. The matches end up in an array, which we join() with '<br>'.
This should do it:
str
.split(' ')
.reduce((accumulator, word, index) =>
accumulator + word + (index !== 0 && index % 5 === 0 ? '<br>' : ' ')
, '');
So what happens here is we split the string into an array of words using the space character. Then we iterate over the array using Array.prototype.reduce and add each word back on to an accumulator string along with a space, or a <br> tag if it the array index is a multiple of 5.
Try like this
let defaultStr = "Hello this is a test string to figure out how is it possible to split a long string into multiple string";
let field = document.getElementById('string');
window.onload = function() {
field.innerHTML = defaultStr;
};
function addBr(){
const arrayWords = defaultStr.split(' ');
let str = '';
let numAddBr = 5;
arrayWords.forEach((value, numberWord) => {
numberWord++;
if(numberWord % numAddBr === 0) str+= '<br>'
str+= `${value} `;
})
field.innerHTML = str
}
<div id="string"></div>
<button onclick="addBr()">add Br</button>
You may use filter with initial result like the first element is final result and the last is the index of the current word, every 5 word, we put the <br> to the final array word and recalculate the current index, the last step is join the word array and replace the unnecessary empty string like this:
let str = "Hello this is a test string to figure out how is it possible to split a long string into multiple string";
let result = str.split(" ").reduce((rs, el) =>
{
if (rs[1] == 5) {
rs[0].push("<br>")
rs[1] = 0
}
else {
rs[0].push(el)
rs[1]++;
}
return rs;
}
,[[], 0]
)[0].join(" ").replace(/ <br>/g, "<br>");
console.log(result);
var str = "Hello this is a test string to figure out how is it possible to split a long string into multiple string";
var new_str="";
str.split(" ").forEach(function (val,i){new_str += val+((i+1)%5==0?"<br>":" ");});
console.log(new_str);
document.write(new_str);
What if multiple spaces are present between two words?
Use this function:
function addtext(str,gap_len,texttoaddbetweenstr){
var new_str="";
str=str.replace(/ {1,}/g," ");
str.split(" ").forEach(function (val,i){new_str += val+((i+1)%gap_len== 0 ? texttoaddbetweenstr:" ");});
return new_str;
}
var str1 = "Hello this is a test string to figure out how is it possible to split a long string into multiple string";
var str_with_multiple_spaces = "Hello this is a test string to figure out how is it possible to split a long string into multiple string";
console.log(addtext(str1,5,"<br>"));
console.log(addtext(str_with_multiple_spaces,5,"<br>"));
console.log(addtext(str1,1,"|"));
console.log("To remove spaces: "+addtext(str1,1,""));

Get everything in string after a single comma [duplicate]

This question already has answers here:
How do I split a string with multiple separators in JavaScript?
(25 answers)
How can I convert a comma-separated string to an array?
(19 answers)
Closed 4 years ago.
I have some problem with my string, the variable name is accountcode. I want only part of the string. I want everything in the string which is after the first ,, excluding any extra space after the comma. For example:
accountcode = "xxxx, tes";
accountcode = "xxxx, hello";
Then I want to output like tes and hello.
I tried:
var s = 'xxxx, hello';
s = s.substring(0, s.indexOf(','));
document.write(s);
Just use split with trim.
var accountcode = "xxxx, tes";
var result= accountcode.split(',')[1].trim();
console.log(result);
You can use String.prototype.split():
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.
You can use length property of the generated array as the last index to access the string item. Finally trim() the string:
var s = 'xxxx, hello';
s = s.split(',');
s = s[s.length - 1].trim();
document.write(s);
You can use string.lastIndexOf() to pull the last word out without making a new array:
let accountcode = "xxxx, hello";
let lastCommaIndex = accountcode.lastIndexOf(',')
let word = accountcode.slice(lastCommaIndex+1).trim()
console.log(word)
You can split the String on the comma.
var s = 'xxxx, hello';
var parts = s.split(',');
console.log(parts[1]);
If you don't want any leading or trailing spaces, use trim.
var s = 'xxxx, hello';
var parts = s.split(',');
console.log(parts[1].trim());
accountcode = "xxxx, hello";
let macthed=accountcode.match(/\w+$/)
if(matched){
document.write(matched[0])
}
here \w+ means any one or more charecter
and $ meand end of string
so \w+$ means get all the character upto end of the sting
so here ' ' space is not a whole character so it started after space upto $
the if statement is required because if no match found than macthed will be null , and it found it will be an array and first element will be your match

Javascript - String split [duplicate]

This question already has answers here:
Javascript and regex: split string and keep the separator
(11 answers)
Closed 6 years ago.
I have the following string
str = "11122+3434"
I want to split it into ["11122", "+", "3434"]. There can be following delimiters +, -, /, *
I have tried the following
strArr = str.split(/[+,-,*,/]/g)
But I get
strArr = [11122, 3434]
Delimiters are things that separate data. So the .split() method is designed to remove delimiters since delimiters are not data so they are not important at all.
In your case, the thing between two values is also data. So it's not a delimiter, it's an operator (in fact, that's what it's called in mathematics).
For this you want to parse the data instead of splitting the data. The best thing for that is therefore regexp:
var result = str.match(/(\d+)([+,-,*,/])(\d+)/);
returns an array:
["11122+3434", "11122", "+", "3434"]
So your values would be result[1], result[2] and result[3].
This should help...
str = '11122+3434+12323*56767'
strArr = str.replace(/[+,-,*,/]/g, ' $& ').split(/ /g)
console.log(strArr)
Hmm, one way is to add a space as delimiter first.
// yes,it will be better to use regex for this too
str = str.replace("+", " + ");
Then split em
strArr = str.split(" ");
and it will return your array
["11122", "+", "3434"]
in bracket +-* need escape, so
strArr = str.split(/[\+\-\*/]/g)
var str = "11122+77-3434";
function getExpression(str) {
var temp = str.split('');
var part = '';
var result = []
for (var i = 0; i < temp.length; i++) {
if (temp[i].match(/\d/) && part.match(/\d/g)) {
part += temp[i];
} else {
result.push(part);
part = temp[i]
}
if (i === temp.length - 1) { //last item
result.push(part);
part = '';
}
}
return result;
}
console.log(getExpression(str))

Function to split a phrase of the form "fooBar" into "foo bar" in javascript? [duplicate]

This question already has answers here:
Split by Caps in Javascript
(4 answers)
Closed 8 years ago.
What's the best way to have a function that takes in a phrase of the form fooBar and returns the words foo bar?
My current approach of iterating over all characters to find a capitalized letter and then splitting on that index seems suboptimal is there a better way?
Thanks!
Your approach is the good one, that is exactly what split function does with this pattern: (?=[A-Z])
var resultArray = mystring.split(/(?=[A-Z])/);
The pattern uses a lookahead assertion (?=...) that means followed by.
Note: if you want to make lowercase all items of the result array, you can map the array like this:
resultArray = resultArray.map(function (x){ return x.toLowerCase(); });
The answer here suffices: Split by Caps in Javascript
Basically use a regex that looks for caps and does a split. To be complete the function is
function splitFooBar() {
var fb = fooBar.split(/(?=[A-Z])/);
fbString = fb.length > 1? fb[0] + " " + fb[1].substr(0, 1).toLowerCase() + fb[1].substr(1): fb[0];
return fbString;
}
try this
var re = /([A-Z])/g;
var str = 'fooBar fooBar fooBarww oldWman ';
var subst = ' $1';
var result = str.replace(re, subst);
result = result.toLowerCase();
console.log(result)
alert(result)

Javascript: Returning the last word in a string

right to it:
I have a words string which has two words in it, and i need to return the last word. They are seperated by a " ". How do i do this?
function test(words) {
var n = words.indexOf(" ");
var res = words.substring(n+1,-1);
return res;
}
I've been told to use indexOf and substring but it's not required. Anyone have an easy way to do this? (with or without indexOf and substring)
Try this:
you can use words with n word length.
example:
words = "Hello World";
words = "One Hello World";
words = "Two Hello World";
words = "Three Hello World";
All will return same value: "World"
function test(words) {
var n = words.split(" ");
return n[n.length - 1];
}
You could also:
words.split(" ").pop();
Just chaining the result (array) of the split function and popping the last element would do the trick in just one line :)
var data = "Welcome to Stack Overflow";
console.log(data.split(" ").splice(-1));
Output
[ 'Overflow' ]
This works even if there is no space in the original string, so you can straight away get the element like this
var data = "WelcometoStackOverflow";
console.log(data.split(" ").splice(-1)[0]);
Output
WelcometoStackOverflow
You want the last word, which suggests lastIndexOf may be more efficient for you than indexOf. Further, slice is also a method available to Strings.
var str = 'foo bar fizz buzz';
str.slice(
str.lastIndexOf(' ') + 1
); // "buzz"
See this jsperf from 2011 showing the split vs indexOf + slice vs indexOf + substring and this perf which shows lastIndexOf is about the same efficiency as indexOf, it mostly depends on how long until the match happens.
To complete Jyoti Prakash, you could add multiple separators (\s|,) to split your string (via this post)
Example:
function lastWord(words) {
var n = words.split(/[\s,]+/) ;
return n[n.length - 1];
}
Note: regex \s means whitespace characters : A space character, A tab character, A carriage return character, A new line character, A vertical tab character, A form feed character
snippet
var wordsA = "Hello Worlda"; // tab
var wordsB = "One Hello\nWorldb";
var wordsC = "Two,Hello,Worldc";
var wordsD = "Three Hello Worldd";
function lastWord(words) {
var n = words.split(/[\s,]+/);
return n[n.length - 1];
}
$('#A').html( lastWord(wordsA) );
$('#B').html( lastWord(wordsB) );
$('#C').html( lastWord(wordsC) );
$('#D').html( lastWord(wordsD) );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
A:<span id="A"></span><br/>
B:<span id="B"></span><br/>
C:<span id="C"></span><br/>
D:<span id="D"></span><br/>
Adding from the accepted answer, if the input string is "Hello World " (note the extra space at the end), it will return ''. The code below should anticipate in case user fat-fingered " ":
var lastWord= function(str) {
if (str.trim() === ""){
return 0;
} else {
var splitStr = str.split(' ');
splitStr = splitStr.filter(lengthFilter);
return splitStr[splitStr.length - 1];
}
};
var lengthFilter = function(str){
return str.length >= 1;
};
Easiest way is to use slice method:-
For example:-
let words = "hello world";
let res = words.slice(6,13);
console.log(res);
/**
* Get last word from a text
* #param {!string} text
* #return {!string}
*/
function getLastWord(text) {
return text
.split(new RegExp("[" + RegExp.quote(wordDelimiters + sentenceDelimiters) + "]+"))
.filter(x => !!x)
.slice(-1)
.join(" ");
}
According to me the easiest way is:
lastName.trim().split(" ").slice(-1)
It will give the last word in a phrase, even if there are trailing spaces.
I used it to show the last name initials. I hope it works for you too.
Use split()
function lastword(words){
array = words.split(' ');
return array[1]
}
Its pretty straight forward.
You have got two words separated by space.
Lets break the string into array using split() method.
Now your array has two elements with indices 0 and 1.
Alert the element with index 1.
var str="abc def";
var arr=str.split(" ");
alert(arr[1]);

Categories