Javascript удалить все переносы строк

Как удалить все разрывы строк из строки

У меня есть текст в текстовой области, и я прочитал его, используя атрибут .value. Теперь я хотел бы удалить все разрывы строк (символ, который появляется при нажатии Enter ) из моего текста, теперь использующего .replace с регулярным выражением, но как я могу указать разрыв строки в регулярном выражении? Если это невозможно, есть ли другой путь?

12 ответов

Это, вероятно, FAQ. Во всяком случае, разрывы строк (лучше: новые строки) могут быть одним из Return Carriage (CR, \r , на старых компьютерах Mac), Line Feed (LF, \n , Unices, включая Linux) или CR, за которым следует LF ( \r\n , на WinDOS). (В отличие от другого ответа, это не имеет никакого отношения к кодировке символов.)

Поэтому наиболее эффективным RegExp литералом для соответствия всем вариантам является

Если вы хотите совместить все строки новой строки в строке, используйте глобальное соответствие,

соответственно. Затем перейдите к методу replace , как это предлагается в нескольких других ответах. (Вероятно, вы не хотите удалять новые строки, но заменяете их на другие пробелы, например символ пробела, чтобы слова оставались неповрежденными.)

Для полноты картины следует отметить, что в Unicode есть четыре разных символа новой строки: \u000a или \n , что является переводом строки; \u000d или \r , который является возвратом каретки; \u2028 , разделитель строк; и \u2029 , разделитель абзацев. Однако на практике регулярное выражение, которое вы разместили, в большинстве случаев достаточно.

@MathiasBynens Спасибо, но U + 2028 и U + 2029 явно не представляют собой разрывы строк в HTML (4.01), на которых основаны дерево DOM и текущее значение текстовой области: w3.org/TR/html4/struct/text.html #whitespace

@PointedEars Да, но сериализация HTML не происходит при динамической установке .value textarea.value = ‘a\u2029b’; textarea.value.charAt(1) == ‘\u2029’; // true , например, textarea.value = ‘a\u2029b’; textarea.value.charAt(1) == ‘\u2029’; // true . Но это, вероятно, крайний случай — как я уже сказал, в большинстве случаев достаточно регулярного выражения.

@MathiasBynens Поскольку U + 2028 и U + 2029 не представляют собой разрывы строк в HTML (4.01), это назначение не отображает две строки в текстовой области с какой-либо основной реализацией DOM и механизмом компоновки. Так что никто в здравом уме не сделает такого назначения в первую очередь.

Мне пришлось избежать обратной косой черты, чтобы это работало для меня, т.е. textIn.replace (/ (\\ r \\ n | \\ n | \\ r) / gm, «»). +1 еще. Спасибо

@CrabBucket Не за что. Но ваша модификация работает только в том случае, если в строке есть буквальные (уже экранированные ) «\ r» и «\ n», или если код передается в eval() или что-то в этом роде (чего вам следует избегать).

То, как вы найдете разрыв строки, зависит от кодировки операционной системы. Windows будет \r\n , но Linux просто использует \n а Apple использует \r .

someText = someText.replace(/(\r\n|\n|\r)/gm, ""); 

Это должно удалить все виды разрывов строк.

Почему разделить \r\n и \n и \r лучше, чем просто /[\n\r]/g ? Конечно, это медленнее, чем должно быть, так как нужно только проверить каждый символ на соответствие двум возможным вариантам.

Читайте также:  Python apply function to list items

При разборе возвращенных данных из memcached в node.js использование / [\ n \ r] / g помогло мне. Спасибо Gone Coding! Вариант в ответе забил на это.

String.trim() удаляет пробелы с начала и конца строк. включая символы новой строки.

const myString = " \n \n\n Hey! \n I'm a string. \n\n"; const trimmedString = myString.trim(); console.log(trimmedString); // outputs: "Hey! \n I'm a string. " 

ЗАМЕТКА! он только обрезает начало и конец строки, а не разрывы строк или пробелы в середине строки.

Вы можете использовать \n в регулярном выражении для строк новой строки и \r для возврата каретки.

В разных операционных системах используются разные концы линий с различными смесями \n и \r . Это регулярное выражение заменит их все.

/\n|\r/g написано более эффективно /[\n\r]/g или даже /[\n\r]+/g . Избегайте чередования, если оно вам абсолютно не нужно.

Не уверен, что это жалоба. Он делает то, что я сказал: удалите ВСЕ, что не в этом диапазоне HEX. Что это за символы, конечно, зависит от набора символов, но этот пост был про ASCII.

Если вы хотите удалить все управляющие символы, включая CR и LF, вы можете использовать это:

Он удалит все непечатаемые символы. Это все символы НЕ в пространстве ASCII HEX 0x20-0x7E . Не стесняйтесь изменять диапазон HEX по мере необходимости.

var str = "bar\r\nbaz\nfoo"; str.replace(/[\r\n]/g, ''); >> "barbazfoo" 

Чтобы удалить символы новой строки, используйте это:

Затем вы можете обрезать вашу строку, чтобы удалить начальные и конечные пробелы:

let str = '\t\n\r this \n \t \r is \r a \n test \t \r \n'; str.replace(/\s+/g, ' ').trim(); console.log(str); // logs: "this is a test" 

.replace() с /\s+/g regexp меняет все группы символов пробелов на единое пространство во всей строке, тогда мы .trim() результат, чтобы удалить все лишние пробелы до и после текста.

считаются символами пробелов:
[ \f\n\r\t\v​\u00a0\u1680​\u2000​-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]

Ответ, предоставленный PointedEars, — это все, что нужно большинству из нас. Но, следуя ответу Матиаса Биненса, я отправился в путешествие по Википедии и нашел его: https://en.wikipedia.org/wiki/Newline.

Ниже приведена функция вставки, которая реализует все, что вышеупомянутая вики-страница считает «новой строкой» во время этого ответа.

Если что-то не подходит для вашего случая, просто удалите это. Кроме того, если вы ищете производительность, это может быть не так, но для быстрого инструмента, который выполняет работу в любом случае, это должно быть полезно.

// replaces all "new line" characters contained in 'someString' with the given 'replacementString' const replaceNewLineChars = ((someString, replacementString = '') => < // defaults to just removing const LF = '\u'; // Line Feed (\n) const VT = '\u'; // Vertical Tab const FF = '\u'; // Form Feed const CR = '\u'; // Carriage Return (\r) const CRLF = '$$'; // (\r\n) const NEL = '\u'; // Next Line const LS = '\u'; // Line Separator const PS = '\u'; // Paragraph Separator const lineTerminators = [LF, VT, FF, CR, CRLF, NEL, LS, PS]; // all Unicode 'lineTerminators' let finalString = someString.normalize('NFD'); // better safe than sorry? Or is it? for (let lineTerminator of lineTerminators) < if (finalString.includes(lineTerminator)) < // check if the string contains the current 'lineTerminator' let regex = new RegExp(lineTerminator.normalize('NFD'), 'gu'); // create the 'regex' for the current 'lineTerminator' finalString = finalString.replace(regex, replacementString); // perform the replacement >; >; return finalString.normalize('NFC'); // return the 'finalString' (without any Unicode 'lineTerminators') >); 

Во-первых — для людей, которые находят, что это не использует JS — «большинство» вкусов RE поддерживают \R что означает «все» переводы строки. Во-вторых, почему бы не просто someString.replace(new RegExp(lineTerminators.join(‘|’)), »);

Читайте также:  Перегрузка операторов python пример

@ClasG, вы делаете хорошую мысль. Я думаю, что когда я писал это, я думал о том, чтобы запускать replace() для lineTerminators которые существовали в строке по соображениям производительности.

Линейная строка в регулярном выражении -\n, поэтому ваш script будет

var test = 'this\nis\na\ntest\nwith\newlines'; console.log(test.replace(/\n/g, ' ')); 

Источник

Javascript remove line breaks from string (4 ways)

While developing in any language, there is a common requirement to remove all the line breaks from a string. This article will talk about removing all the line breaks from a javascript string using different methods and example illustrations. The article also shows how to remove line breaks from the start and end of a javascript string.

Table of Contents:-

Javascript string remove all line breaks using replace() and RegExp

Javascript’s replace() method finds a pattern and replaces some or all of its occurrences with a replacement(character/string). The pattern can be a character or a string, or regExp.

RegExp is the regular expression object. Theses objects are patterns used to match character combinations in strings.

Frequently Asked:

Remove all line breaks from the string “\n Javascript \nis a popular \nlanguage \n”

let dummyString = " \n Javascript \nis a popular \nlanguage \n" let stringWithoutLineBreaks = dummyString.replace(/(\r\n|\n|\r)/gm, '') console.log("Original String: "+ dummyString ) console.log("Final String: "+ stringWithoutLineBreaks)

Here in the above code, we are using replace() method with RegExp. The regular expression is the first argument stating that this replace() method should replace all line breaks found in the string on which the method is applied. The second argument is the replacement, nothing (”) in our case.

Where \n is for line feed and \r for carriage return

Original String: Javascript is a popular language Final String: Javascript is a popular language

Javascript string remove all line breaks using replaceAll()

Javascript’s replaceAll() method will replace all the pattern matches within a string with a replacement. The first argument is a pattern which can be a string or a RegExp. This first argument is to be searched in string and replaced with a replacement. The second argument is a replacement which can be a string or a function.

Remove all line breaks from the string “\n Javascript \nis a popular \nlanguage \n”

Here the below code uses the replaceAll() method to replace all the occurrences of the line break. Line feed (\n) is passed as the first argument and a replacement is passed as the second argument, nothing (”) in our case.

let dummyString = " \n Javascript\n is a popular \nlanguage \n" let stringWithoutLineBreaks = dummyString.replaceAll('\n','') console.log("Original String: "+ dummyString ) console.log("Final String: "+ stringWithoutLineBreaks)
Original String: Javascript is a popular language Final String: Javascript is a popular language

Javascript string remove all line breaks using split() and join()

The split() method in javascript returns an array of substrings formed by splitting a given string.

The join() method in javascript joins the elements of the array back into a string.

Remove all line breaks from the string “\n Javascript \nis a popular \nlanguage \n”

The below code shows that we split the original string based on line break (\n) using the split() method into an array of substrings. The array formed will have the elements . Then join the array back into one string using the join() method.

let dummyString = " \n Javascript\n is a popular \nlanguage \n" let stringWithoutLineBreaks = dummyString.split('\n').join('') console.log("Original String: "+ dummyString ) console.log("Final String: "+ stringWithoutLineBreaks)
Original String: Javascript is a popular language Final String: Javascript is a popular language

Javascript string remove line breaks from start and end of the string

Javascript’s trim() method removes all the white space characters from the start and end. These whitespace characters include space, tab, line breaks, etc.

Remove the line breaks only from the start and end of the string “\n Javascript \nis a popular \nlanguage \n”

Here, in the below code, we are using the trim() method to remove the line breaks from the start and end of the string.

let dummyString = " \n Javascript \nis a popular \nlanguage \n" let finalString = dummyString.trim() console.log("Original String: "+ dummyString ) console.log("Final String: "+ finalString)
Original String: Javascript is a popular language Final String: Javascript is a popular language

I hope this article helped you to delete line breaks from a string in javascript. Good Luck .

Share your love

Leave a Comment Cancel Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Читайте также:  Tkinter python удалить элемент

Terms of Use

Disclaimer

Copyright © 2023 thisPointer

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.

The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.

The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.

The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.

Источник

Оцените статью